Search Results

Search found 46 results on 2 pages for 'binarywriter'.

Page 1/2 | 1 2  | Next Page >

  • Async BinaryWriter ?

    - by blez
    I found implementation of async BinaryWriter here: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/11f6aa76-1383-4cab-8693-29dcb25bbf2e But I can't really use it. I change all my types to AsyncBinaryWriter and I use .Write, but no data is written to the stream. Is that the proper way for using it ?

    Read the article

  • Does binarywriter.flush() also flush the underlying filestream object?

    - by jacob sebastian
    I have got a code snippet as follows: Dim fstream = new filestream(some file here) dim bwriter = new binarywriter(fstream) while not end of file read from source file bwriter.write() bwriter.flush() end while The question I have is the following. When I call bwriter.flush() does it also flush the fstream object? Or should I have to explicitly call fstream.flush() such as given in the following example: while not end of file read from source file bwriter.write() bwriter.flush() fstream.flush() end while A few people suggested that I need to call fstream.flush() explicitly to make sure that the data is written to the disk (or the device). However, my testing shows that the data is written to the disk as soon as I call flush() method on the bwriter object. Can some one confirm this?

    Read the article

  • Excel 2007 file writer in C# results in a corrupt file

    - by Martin
    Hi, I am using a BinaryReader to read an Excel 2007 file from an Exchange mailbox using a OWA, the file is then written to disk using a BinaryWriter. My problem is that the two files don't match when the writer finishes. Worse still Excel 2007 won't open the writen file. Previously Excel 2003 has had no problem with the solution below. And Excel 2007 doesn't have an issue if the file is an Excel 2003 format file, only if the file format is Excel 2007 (*.xlsx). BinaryReader: using(System.IO.Stream stream = resource.GetInputStream(attachedFiles[k].Address)) { using(System.IO.BinaryReader br = new System.IO.BinaryReader(stream)) { attachment.Data = new byte[attachedFiles[k].Size]; int bufPosn=0, len=0; while ((len = br.Read( attachment.Data, bufPosn, attachment.Data.Length-bufPosn )) > 0) { bufPosn += len; } br.Close(); } } BinaryWriter: FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter binWriter = new BinaryWriter(fs); binWriter.Write( content, 0, content.Length ); binWriter.Close(); fs.Close(); Suggestions gratfully received.

    Read the article

  • classic asp: display jpg using response.BinaryWrite

    - by Fuxi
    hi, i'm displaying an image like this: <img src='counter.asp'> counter.asp is doing a hitcounter do determine how often the image was displayed (i'll replace it with a modrewrite url). the problem: in the counter.asp script i need to send the actual .jpg image to the browser, how could this be done? i suppose i need to load the image through FSO then send it using Response.BinaryWrite - any ideas? thanks

    Read the article

  • Is Stream.Write thread-safe?

    - by Mike Spross
    I'm working on a client/server library for a legacy RPC implementation and was running into issues where the client would sometimes hang when waiting to a receive a response message to an RPC request message. It turns out the real problem was in my message framing code (I wasn't handling message boundaries correctly when reading data off the underlying NetworkStream), but it also made me suspicious of the code I was using to send data across the network, specifically in the case where the RPC server sends a large amount of data to a client as the result of a client RPC request. My send code uses a BinaryWriter to write a complete "message" to the underlying NetworkStream. The RPC protocol also implements a heartbeat algorithm, where the RPC server sends out PING messages every 15 seconds. The pings are sent out by a separate thread, so, at least in theory, a ping can be sent while the server is in the middle of streaming a large response back to a client. Suppose I have a Send method as follows, where stream is a NetworkStream: public void Send(Message message) { //Write the message to a temporary stream so we can send it all-at-once MemoryStream tempStream = new MemoryStream(); message.WriteToStream(tempStream); //Write the serialized message to the stream. //The BinaryWriter is a little redundant in this //simplified example, but here because //the production code uses it. byte[] data = tempStream.ToArray(); BinaryWriter bw = new BinaryWriter(stream); bw.Write(data, 0, data.Length); bw.Flush(); } So the question I have is, is the call to bw.Write (and by implication the call to the underlying Stream's Write method) atomic? That is, if a lengthy Write is still in progress on the sending thread, and the heartbeat thread kicks in and sends a PING message, will that thread block until the original Write call finishes, or do I have to add explicit synchronization to the Send method to prevent the two Send calls from clobbering the stream?

    Read the article

  • Session state provider and global.asax not interacting properly?

    - by yodaj007
    I'm experimenting with creating a crude, proof-of-concept session state store provider in ASP.Net. But I've got a problem and I'm not sure what to do about it. The website works properly when using the InProc provider. The Session_Start in global.asax is called on session creation as it should. But not if I implement my own provider. The Session_Start method from global.asax isn't being called at all if a new session is being created (that is, I delete the session state file). Am I missing something important here? public class TestSessionProvider : SessionStateStoreProviderBase { private const string ROOT = "c:\\projects\\sessions\\"; private const int TIMEOUT_MINUTES = 30; public string ApplicationName { get { return HostingEnvironment.ApplicationVirtualPath; } } private string GetFilename(string id) { string filename = String.Format("{0}_{1}.session", ApplicationName, id); char[] invalids = Path.GetInvalidPathChars(); for (int i = 0; i < invalids.Length; i++) { filename = filename.Replace(invalids[i], '_'); } return Path.Combine(ROOT, Path.GetFileName(filename)); } public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (String.IsNullOrEmpty(name)) name = "Sporkalicious"; base.Initialize(name, config); } public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout) { SessionStateItemCollection items = new SessionStateItemCollection(); HttpStaticObjectsCollection objects = SessionStateUtility.GetSessionStaticObjects(context); return new SessionStateStoreData(items, objects, TIMEOUT_MINUTES); } /// <summary> /// The CreateUninitializedItem method is used with cookieless sessions when the regenerateExpiredSessionId /// attribute is set to true, which causes SessionStateModule to generate a new SessionID value when an /// expired session ID is encountered. /// </summary> /// <param name="context"></param> /// <param name="id"></param> /// <param name="timeout"></param> public override void CreateUninitializedItem(HttpContext context, string id, int timeout) { FileStream fs = File.Open(GetFilename(id), FileMode.CreateNew, FileAccess.Write, FileShare.None); BinaryWriter writer = new BinaryWriter(fs); SessionStateItemCollection coll = new SessionStateItemCollection(); coll.Serialize(writer); fs.Flush(); fs.Close(); } public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { return GetItemExclusive(context, id, out locked, out lockAge, out lockId, out actions); } public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { locked = false; lockAge = TimeSpan.FromDays(1); lockId = 0; actions = SessionStateActions.None; if (!File.Exists(GetFilename(id))) { return null; } FileStream fs = File.Open(GetFilename(id), FileMode.Open, FileAccess.ReadWrite, FileShare.Read); BinaryReader reader = new BinaryReader(fs); SessionStateItemCollection coll = SessionStateItemCollection.Deserialize(reader); fs.Close(); return new SessionStateStoreData(coll, new HttpStaticObjectsCollection(), TIMEOUT_MINUTES); } public override void ReleaseItemExclusive(HttpContext context, string id, object lockId) { } public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item) { File.Delete(GetFilename(id)); } public override void ResetItemTimeout(HttpContext context, string id) { } public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { if (!File.Exists(GetFilename(id))) { CreateUninitializedItem(context, id, 10); } FileStream fs = File.Open(GetFilename(id), FileMode.Truncate, FileAccess.Write, FileShare.None); BinaryWriter writer = new BinaryWriter(fs); SessionStateItemCollection coll = (SessionStateItemCollection)item.Items; coll.Serialize(writer); fs.Flush(); fs.Close(); } public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { return false; } public override void InitializeRequest(HttpContext context){} public override void EndRequest(HttpContext context){} public override void Dispose(){} }

    Read the article

  • BizTalk Pipeline Component Error: "Object reference not set to an instance of an object"

    - by Stuart Brierley
    Yesterday I posted about my BizTalk Archiving Pipeline Component, which can be found on Codeplex if anyone is interested in taking a look. During testing of this component I began to encounter an error whereby the component would throw an "Object reference not set to an instance of an object" error when processing as a part of a Custom Pipeline. This was occurring when the component was reading a ReadOnlySeekableStream so that the data can be archived to file, but the actual code throwing the error was somewhere in the depths of the Microsoft.BizTalk.Streaming stack. It turns out that there is a known issue where this exception can be thrown because the garbage collector has disposed of of the stream before execution of the custom pipeline has completed. To get around this you need to add the streams in your code to the pipeline context resource tracker.   So a block of my code goes from:                         originalStrm = bodyPart.GetOriginalDataStream();                         if (!originalStrm.CanSeek)                         {                             ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(originalStrm);                             inmsg.BodyPart.Data = seekableStream;                             originalStrm = inmsg.BodyPart.Data;                         }                         fileArchive = new FileStream(FullPath, FileMode.Create, FileAccess.Write);                         binWriter = new BinaryWriter(fileArchive);                         byte[] buffer = new byte[bufferSize];                         int sizeRead = 0;                         while ((sizeRead = originalStrm.Read(buffer, 0, bufferSize)) != 0)                         {                             binWriter.Write(buffer, 0, sizeRead);                         } to                         originalStrm = bodyPart.GetOriginalDataStream();                         if (!originalStrm.CanSeek)                         {                             ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(originalStrm);                             inmsg.BodyPart.Data = seekableStream;                             originalStrm = inmsg.BodyPart.Data;                         }                         pc.ResourceTracker.AddResource(originalStrm);                         fileArchive = new FileStream(FullPath, FileMode.Create, FileAccess.Write);                         binWriter = new BinaryWriter(fileArchive);                         byte[] buffer = new byte[bufferSize];                         int sizeRead = 0;                         while ((sizeRead = originalStrm.Read(buffer, 0, bufferSize)) != 0)                         {                             binWriter.Write(buffer, 0, sizeRead);                         } So far this seems to have solved the issue, the error is no more, and my archive component is continuing its way through testing.

    Read the article

  • binary file to string

    - by andrew
    i'm trying to read a binary file (for example an executable) into a string, then write it back FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open); BinaryReader br = new BinaryReader(fs); byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length)); System.Text.Encoding enc = System.Text.Encoding.ASCII; string myString = enc.GetString(bin); fs.Close(); br.Close(); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] rebin = encoding.GetBytes(myString); FileStream fs2 = new FileStream("C:\\tvout.exe", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs2); bw.Write(rebin); fs2.Close(); bw.Close(); this does not work (the result has exactly the same size in bytes but can't run) if i do bw.Write(bin) the result is ok, but i must save it to a string

    Read the article

  • Why its not working?

    - by Andrew Hoffmann
    BinaryReader br = new BinaryReader(Console.OpenStandardInput()); BinaryWriter bw = new BinaryWriter(Console.OpenStandardOutput()); int n = br.ReadInt32(); bw.Write(n); always getting this error: Unhandled Exception: System.IO.EndOfStreamException: Failed to read past end of stream. at System.IO.BinaryReader.FillBuffer (Int32 numBytes) [0x00000] in <filename unknown>:0 at System.IO.BinaryReader.ReadInt32 () [0x00000] in <filename unknown>:0 at Program.Main () [0x00025] in /home/skydos/ACM/Csharp/Csharp/Main.cs:24 Is there any way to make reading data in C# faster from Console?

    Read the article

  • Creating a binary file from an IntelHex in C#

    - by Allek
    I'm trying to create a binary file from a intelHex file. Iside the intelHex file I have data and address to which I should write the data inside the binary file. IntelHex file looks like that :10010000214601360121470136007EFE09D2190140 :100110002146017EB7C20001FF5F16002148011988 :10012000194E79234623965778239EDA3F01B2CAA7 :100130003F0156702B5E712B722B732146013421C7 :00000001FF So I have 4 lines here with data since the last one tells us thats the end of file. Here is what I'm doing to create the file while (!streamReader.EndOfStream) { string temp = String.Empty; int address = 0; line = streamReader.ReadLine(); // Get address for each data address = Convert.ToInt32(line.Substring(3, 4), 16); // Get data from each line temp = line.Substring(7, 2); if (temp == "01") break; else { temp = line.Substring(9, line.Length - 11); string[] array = new string[(temp.Length / 2)]; int j = 0; for (int i = 0; i < array.Length; ++i) { array[i] = temp[j].ToString() + temp[j + 1].ToString(); j = j + 2; } temp = String.Empty; for (int i = 0; i < array.Length; ++i) { temp = temp + Convert.ToChar(Convert.ToInt32(array[i], 16)); } } binaryWriter.Seek(address, SeekOrigin.Begin); binaryWriter.Write(temp); binaryWriter.Flush(); } Console.WriteLine("Done...\nPress any key to exit..."); The problem here is, that data in binary file in some places is not equal to data from the intelHex file. Looks like there is some random data added to the file and I do not know from where. First time I saw that there is an additional data before the data from the intelHex file. For instance first data line starts with 21, but in binary file I have a number 12 before the 21. I do not know what is wrong here. Hope someone can help me or guide me where I can find some usefull informations about creating binary files in C#

    Read the article

  • Serialize a C# class to binary be used by C++. How to handle alignment?

    - by glenn.danthi
    I am currently serializing a C# class into a binary stream using BinaryWriter. I take each element of the class and write it out using BinaryWriter. This worked fine as the C++ application reading this binary file supported packed structs and hence the binary file could be loaded directly. Now I have got a request to handle alignment as a new application has popped up which cannot support packed structs. What's the best way to convert the C# class and exporting it out as a binary keeping both 2 byte as well as 4 byte alignment in mind? The user can choose the alignment.

    Read the article

  • C# Error reading two dates from a binary file

    - by Jamie
    Hi all, When reading two dates from a binary file I'm seeing the error below: "The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text.DecoderReplacementFallback'. Parameter name: chars" My code is below: static DateTime[] ReadDates() { System.IO.FileStream appData = new System.IO.FileStream( appDataFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); List<DateTime> result = new List<DateTime>(); using (System.IO.BinaryReader br = new System.IO.BinaryReader(appData)) { while (br.PeekChar() > 0) { result.Add(new DateTime(br.ReadInt64())); } br.Close(); } return result.ToArray(); } static void WriteDates(IEnumerable<DateTime> dates) { System.IO.FileStream appData = new System.IO.FileStream( appDataFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); List<DateTime> result = new List<DateTime>(); using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(appData)) { foreach (DateTime date in dates) bw.Write(date.Ticks); bw.Close(); } } What could be the cause? Thanks

    Read the article

  • Is it possible to store controls(Panel) as object, serialize it and store it as a file?

    - by ikky
    The topic says it all. Using Compact Framework C# I'm tiling (order/sequence is important) some images that i download from an url, into a Panel(each image is a PictureBox). This can be a huge process, and may take some time. Therefor i only want the user to download the images and tile them once. So the next time the user uses the Tile Application, the Panel that was created the first time is already stored in a file and is loaded from that file. So what i want is a method to store a Panel as a file. Is this possible, or do you think i should do it another way? I've tried something like this: BinaryWriter panelStorage = new BinaryWriter(new FileStream("imagePanel.panel", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)); Byte[] bImageObject = new Byte[20000]; bImageObject = (byte[])(object)this.imagePanel; panelStorage .Write(bMapObject); panelStorage .Close(); But the casting was not very legal :P "InvalidCastException" Can anyone help me with this problem? Thank you in advance!

    Read the article

  • CIL and JVM Little endian to big endian in c# and java

    - by Haythem
    Hello, I am using on the client C# where I am converting double values to byte array. I am using java on the server and I am using writeDouble and readDouble to convert double values to byte arrays. The problem is the double values from java at the end are not the double values at the begin giving to c# writeDouble in Java Converts the double argument to a long using the doubleToLongBits method , and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first. DoubleToLongBits Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout. The Program on the server is waiting of 64-102-112-0-0-0-0-0 from C# to convert it to 1700.0 but he si becoming 0000014415464 from c# after c# converted 1700.0 this is my code in c#: class User { double workingStatus; public void persist() { byte[] dataByte; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(workingStatus); bw.Flush(); bw.Close(); } dataByte = ms.ToArray(); for (int j = 0; j < dataByte.Length; j++) { Console.Write(dataByte[j]); } } public double WorkingStatus { get { return workingStatus; } set { workingStatus = value; } } } class Test { static void Main() { User user = new User(); user.WorkingStatus = 1700.0; user.persist(); } thank you for the help.

    Read the article

  • How Can I Generate Equivalent Output Using the CryptoAPI and the .NET Encryption (TripleDESCryptoSer

    - by S. Butts
    I have some C#/.NET code that encrypts and decrypts data using TripleDES encryption. It sticks to the sample code provided at MSDN pretty closely. The encryption piece looks like the following: TripleDESCryptoServiceProvider _desProvider = new TripleDESCryptoServiceProvider(); //bytes for key and initialization vector //keyBytes is 24 bytes of stuff, vectorBytes is 8 bytes of stuff byte[] keyBytes; byte[] vectorBytes; FileStream fStream = File.Open(locationOfFile, FileMode.Create, FileAccess.Write); CryptoStream cStream = new CryptoStream(fStream, _desProvider.CreateEncryptor(keyBytes, vectorBytes), CryptoStreamMode.Write); BinaryWriter bWriter = new BinaryWriter(cStream); //write out encrypted data //raw data is a few bytes of binary information byte[] rawData; bWriter.Write(rawData); With encrypting and decrypting in C#, this all works like a charm. The problem is I need to write a small Win32 utility that will duplicate the encryption above. I have tried several methods using the CryptoAPI, and I simply do not get output that the .NET piece can decrypt, no matter what I do. Can someone please tell me what the equivalent C++ code is that will produce the same output? I am not certain just what methods of the CryptoAPI the .NET functions use to encrypt the data. What options are used, and what method of generating the key is used? Before someone suggests that I just write it in C# anyway, or create some common library bridge for them, those options are unfortunately off the table. It really has to work in Win32 with .NET and without using a DLL. I have some leeway in changing the C# code. I apologize in advance if this is bone-headed, as I am new to encryption.

    Read the article

  • How to File Transfer client to Server?

    - by Phsika
    i try to recieve a file from server but give me error on server.Start() ERROR : In a manner not permitted by the access permissions to access a socket was attempted to How can i solve it? private void btn_Recieve_Click(object sender, EventArgs e) { TcpListener server = null; // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("192.168.1.201"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[277577]; String data; data = null; // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); int i; i = stream.Read(bytes, 0, 277577); BinaryWriter writer = new BinaryWriter(File.Open("GoodLuckToMe.jpg", FileMode.Create)); writer.Write(bytes); writer.Close(); client.Close(); }

    Read the article

  • What am I doing wrong with HttpResponse content and headers when downloading a file?

    - by Slauma
    I want to download a PDF file from a SQL Server database which is stored in a binary column. There is a LinkButton on an aspx page. The event handler of this button looks like this: protected void LinkButtonDownload(object sender, EventArgs e) { ... byte[] aByteArray; // Read binary data from database into this ByteArray // aByteArray has the size: 55406 byte Response.ClearHeaders(); Response.ClearContent(); Response.BufferOutput = true; Response.AddHeader("Content-Disposition", "attachment; filename=" + "12345.pdf"); Response.ContentType = "application/pdf"; using (BinaryWriter aWriter = new BinaryWriter(Response.OutputStream)) { aWriter.Write(aByteArray, 0, aByteArray.Length); } } A "File Open/Save dialog" is offered in my browser. When I store this file "12345.pdf" to disk, the file has a size of 71523 Byte. The additional 16kB at the end of the PDF file are the HTML code of my page (as I can see when I view the file in an editor). I am confused because I was believing that ClearContent and ClearHeaders would ensure that the page content is not sent together with the file content. What am I doing wrong here? Thanks for help!

    Read the article

  • How can I create an Image in GDI+ from a Base64-Encoded string in C++?

    - by Schnapple
    I have an application, currently written in C#, which can take a Base64-encoded string and turn it into an Image (a TIFF image in this case), and vice versa. In C# this is actually pretty simple. private byte[] ImageToByteArray(Image img) { MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff); return ms.ToArray(); } private Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); BinaryWriter bw = new BinaryWriter(ms); bw.Write(byteArrayIn); Image returnImage = Image.FromStream(ms, true, false); return returnImage; } // Convert Image into string byte[] imagebytes = ImageToByteArray(anImage); string Base64EncodedStringImage = Convert.ToBase64String(imagebytes); // Convert string into Image byte[] imagebytes = Convert.FromBase64String(Base64EncodedStringImage); Image anImage = byteArrayToImage(imagebytes); (and, now that I'm looking at it, could be simplified even further) I now have a business need to do this in C++. I'm using GDI+ to draw the graphics (Windows only so far) and I already have code to decode the string in C++ (to another string). What I'm stumbling on, however, is getting the information into an Image object in GDI+. At this point I figure I need either a) A way of converting that Base64-decoded string into an IStream to feed to the Image object's FromStream function b) A way to convert the Base64-encoded string into an IStream to feed to the Image object's FromStream function (so, different code than I'm currently using) c) Some completely different way I'm not thinking of here. My C++ skills are very rusty and I'm also spoiled by the managed .NET platform, so if I'm attacking this all wrong I'm open to suggestions.

    Read the article

  • How can i get a file from remote machine?

    - by programmerist
    How can i get a file from remote computer? i know remote computer ip and 51124 port is open. i need this algorith: 1) Connect 192.xxx.x.xxx ip via 51124 port 2) filename:123456 (i want to search it on remote machine) 3) Get File 4) Save C:\ 51124 port is open. can i access and can i search any file according to filename? My code is below: IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 51124); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); sock.Bind(ipEnd); sock.Listen(maxConnections); Socket serverSocket = sock.Accept(); byte[] data = new byte[bufferSize]; int received = serverSocket.Receive(data); int filenameLength = BitConverter.ToInt32(data, 0); string filename = Encoding.ASCII.GetString(data, 4, filenameLength); BinaryWriter bWrite = new BinaryWriter(File.Open(outPath + filename, FileMode.Create)); bWrite.Write(data, filenameLength + 4, received - filenameLength - 4); int received2 = serverSocket.Receive(data); while (received2 0) { bWrite.Write(data, 0, received2); received2 = serverSocket.Receive(data); } bWrite.Close(); serverSocket.Close(); sock.Close();

    Read the article

  • Reading and writing in parallel

    - by Malfist
    I want to be able to read and write a large file in parallel, or if not in parallel, at least in blocks so that I don't use up so much memory. This is my current code: // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(); // Define cryptographic stream (always use Write mode for encryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); //start encrypting using (BinaryReader reader = new BinaryReader(File.Open(fileIn, FileMode.Open))) { byte[] buffer = new byte[1024 * 1024]; int read = 0; do { read = reader.Read(buffer, 0, buffer.Length); cryptoStream.Write(buffer, 0, read); } while (read == buffer.Length); } // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memory stream into a byte array. //byte[] cipherTextBytes = memoryStream.ToArray(); //write our memory stream to a file memoryStream.Position = 0; using (BinaryWriter writer = new BinaryWriter(File.Open(fileOut, FileMode.Create))) { byte[] buffer = new byte[1024 * 1024]; int read = 0; do { read = memoryStream.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, read); } while (read == buffer.Length); } // Close both streams. memoryStream.Close(); cryptoStream.Close(); As you can see, it reads the entire file into memory, encrypts it, then writes it out. If I happen to be encrypting files that are very large (2GB+) it tends not to work, or at the very least, consumes ~97% of my memory. How could I do it in a more effective manner?

    Read the article

  • How to strip out 0x0a special char from utf8 file using c# and keep file as utf8?

    - by user1013388
    The following is a line from a UTF-8 file from which I am trying to remove the special char (0X0A), which shows up as a black diamond with a question mark below: 2464577 ????? True s6620178 Unspecified <1?1009-672 This is generated when SSIS reads a SQL table then writes out, using a flat file mgr set to code page 65001. When I open the file up in Notepad++, displays as 0X0A. I'm looking for some C# code to definitely strip that char out and replace it with either nothing or a blank space. Here's what I have tried: string fileLocation = "c:\\MyFile.txt"; var content = string.Empty; using (StreamReader reader = new System.IO.StreamReader(fileLocation)) { content = reader.ReadToEnd(); reader.Close(); } content = content.Replace('\u00A0', ' '); //also tried: content.Replace((char)0X0A, ' '); //also tried: content.Replace((char)0X0A, ''); //also tried: content.Replace((char)0X0A, (char)'\0'); Encoding encoding = Encoding.UTF8; using (FileStream stream = new FileStream(fileLocation, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(stream, encoding)) { writer.Write(encoding.GetPreamble()); //This is for writing the BOM writer.Write(content); } } I also tried this code to get the actual string value: byte[] bytes = { 0x0A }; string text = Encoding.UTF8.GetString(bytes); And it comes back as "\n". So in the code above I also tried replacing "\n" with " ", both in double quotes and single quotes, but still no change. At this point I'm out of ideas. Anyone got any advice? Thanks.

    Read the article

  • Wrong encoding in DataReceivedEventArgs

    - by user2102508
    I start cmd.exe process and redirect stdin to pass script to it and redirect stdout and stderr to read cmd's output. Here is the code of my DataReceivedEventHandler: (o, a) => { if(!String.IsNullOrEmpty(a.Data)) { bw.Write(a.Data.ToUTF8()); bw.Write((byte)'\n'); } } In the code bw is instance of BinaryWriter, ToUTF8 is string extension method, that converts a string to UTF8 encoded byte array. When I use this code in a separate process it works well, however when I use this code as a shared library inside some other process a.Data doesn't contain valid localized characters (like russian characters for example). So how should I convert characters? How to get cmd's OEM encoding? Why does the code works well in a separate process and doesn't work as a shared library inside some other process?

    Read the article

  • Developing Schema Compare for Oracle (Part 5): Query Snapshots

    - by Simon Cooper
    If you've emailed us about a bug you've encountered with the EAP or beta versions of Schema Compare for Oracle, we probably asked you to send us a query snapshot of your databases. Here, I explain what a query snapshot is, and how it helps us fix your bug. Problem 1: Debugging users' bug reports When we started the Schema Compare project, we knew we were going to get problems with users' databases - configurations we hadn't considered, features that weren't installed, unicode issues, wierd dependencies... With SQL Compare, users are generally happy to send us a database backup that we can restore using a single RESTORE DATABASE command on our test servers and immediately reproduce the problem. Oracle, on the other hand, would be a lot more tricky. As Oracle generally has a 1-to-1 mapping between instances and databases, any databases users sent would have to be restored to their own instance. Furthermore, the number of steps required to get a properly working database, and the size of most oracle databases, made it infeasible to ask every customer who came across a bug during our beta program to send us their databases. We also knew that there would be lots of issues with data security that would make it hard to get backups. So we needed an easier way to be able to debug customers issues and sort out what strange schema data Oracle was returning. Problem 2: Test execution time Another issue we knew we would have to solve was the execution time of the tests we would produce for the Schema Compare engine. Our initial prototype showed that querying the data dictionary for schema information was going to be slow (at least 15 seconds per database), and this is generally proportional to the size of the database. If you're running thousands of tests on the same databases, each one registering separate schemas, not only would the tests would take hours and hours to run, but the test servers would be hammered senseless. The solution To solve these, we needed to be able to populate the schema of a database without actually connecting to it. Well, the IDataReader interface is the primary way we read data from an Oracle server. The data dictionary queries we use return their data in terms of simple strings and numbers, which we then process and reconstruct into an object model, and the results of these queries are identical for identical schemas. So, we can record the raw results of the queries once, and then replay these results to construct the same object model as many times as required without needing to actually connect to the original database. This is what query snapshots do. They are binary files containing the raw unprocessed data we get back from the oracle server for all the queries we run on the data dictionary to get schema information. The core of the query snapshot generation takes the results of the IDataReader we get from running queries on Oracle, and passes the row data to a BinaryWriter that writes it straight to a file. The query snapshot can then be replayed to create the same object model; when the results of a specific query is needed by the population code, we can simply read the binary data stored in the file on disk and present it through an IDataReader wrapper. This is far faster than querying the server over the network, and allows us to run tests in a reasonable time. They also allow us to easily debug a customers problem; using a simple snapshot generation program, users can generate a query snapshot that could be sent along with a bug report that we can immediately replay on our machines to let us debug the issue, rather than having to obtain database backups and restore databases to test systems. There are also far fewer problems with data security; query snapshots only contain schema information, which is generally less sensitive than table data. Query snapshots implementation However, actually implementing such a feature did have a couple of 'gotchas' to it. My second blog post detailed the development of the dependencies algorithm we use to ensure we get all the dependencies in the database, and that algorithm uses data from both databases to find all the needed objects - what database you're comparing to affects what objects get populated from both databases. We get information on these additional objects using an appropriate WHERE clause on all the population queries. So, in order to accurately replay the results of querying the live database, the query snapshot needs to be a snapshot of a comparison of two databases, not just populating a single database. Furthermore, although the code population queries (eg querying all_tab_cols to get column information) can simply be passed straight from the IDataReader to the BinaryWriter, we need to hook into and run the live dependencies algorithm while we're creating the snapshot to ensure we get the same WHERE clauses, and the same query results, as if we were populating straight from a live system. We also need to store the results of the dependencies queries themselves, as the resulting dependency graph is stored within the OracleDatabase object that is produced, and is later used to help order actions in synchronization scripts. This is significantly helped by the dependencies algorithm being a deterministic algorithm - given the same input, it will always return the same output. Therefore, when we're replaying a query snapshot, and processing dependency information, we simply have to return the results of the queries in the order we got them from the live database, rather than trying to calculate the contents of all_dependencies on the fly. Query snapshots are a significant feature in Schema Compare that really helps us to debug problems with the tool, as well as making our testers happier. Although not really user-visible, they are very useful to the development team to help us fix bugs in the product much faster than we otherwise would be able to.

    Read the article

  • Get/open temp file in .NET

    - by acidzombie24
    I would like to do something like the below. What function returns me an unique file that is opened? so i can ensure it is mine and i wont overwrite anything or write a complex fn generate/loop BinaryWriter w = GetTempFile(out fn); w.close(); File.Move(fn, newFn);

    Read the article

  • Whats wrong with my triple DES wrapper??

    - by Chen Kinnrot
    it seems that my code adds 6 bytes to the result file after encrypt decrypt is called.. i tries it on a mkv file.. please help here is my code class TripleDESCryptoService : IEncryptor, IDecryptor { public void Encrypt(string inputFileName, string outputFileName, string key) { EncryptFile(inputFileName, outputFileName, key); } public void Decrypt(string inputFileName, string outputFileName, string key) { DecryptFile(inputFileName, outputFileName, key); } static void EncryptFile(string inputFileName, string outputFileName, string sKey) { var outFile = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); // The chryptographic service provider we're going to use var cryptoAlgorithm = new TripleDESCryptoServiceProvider(); SetKeys(cryptoAlgorithm, sKey); // This object links data streams to cryptographic values var cryptoStream = new CryptoStream(outFile, cryptoAlgorithm.CreateEncryptor(), CryptoStreamMode.Write); // This stream writer will write the new file var encryptionStream = new BinaryWriter(cryptoStream); // This stream reader will read the file to encrypt var inFile = new FileStream(inputFileName, FileMode.Open, FileAccess.Read); var readwe = new BinaryReader(inFile); // Loop through the file to encrypt, line by line var date = readwe.ReadBytes((int)readwe.BaseStream.Length); // Write to the encryption stream encryptionStream.Write(date); // Wrap things up inFile.Close(); encryptionStream.Flush(); encryptionStream.Close(); } private static void SetKeys(SymmetricAlgorithm algorithm, string key) { var keyAsBytes = Encoding.ASCII.GetBytes(key); algorithm.IV = keyAsBytes.Take(algorithm.IV.Length).ToArray(); algorithm.Key = keyAsBytes.Take(algorithm.Key.Length).ToArray(); } static void DecryptFile(string inputFilename, string outputFilename, string sKey) { // The encrypted file var inFile = File.OpenRead(inputFilename); // The decrypted file var outFile = new FileStream(outputFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite); // Prepare the encryption algorithm and read the key from the key file var cryptAlgorithm = new TripleDESCryptoServiceProvider(); SetKeys(cryptAlgorithm, sKey); // The cryptographic stream takes in the encrypted file var encryptionStream = new CryptoStream(inFile, cryptAlgorithm.CreateDecryptor(), CryptoStreamMode.Read); // Write the new unecrypted file var cleanStreamReader = new BinaryReader(encryptionStream); var cleanStreamWriter = new BinaryWriter(outFile); cleanStreamWriter.Write(cleanStreamReader.ReadBytes((int)inFile.Length)); cleanStreamWriter.Close(); outFile.Close(); cleanStreamReader.Close(); } }

    Read the article

1 2  | Next Page >