![]() Write() method of the FileStream handles writing the bytes, and it's only doing it one byte at a time, so it won't clog memory, except that you will have to have enough memory to hold the stream as a byte object. It might be slower doing it this way, as a result. CopyTo() or equivalent allows FileStream to stream it instead of using a byte array and reading the bytes one by one. Only potential downsides I can see in doing it this way is if there's a large file you have, having it as a stream and using. One stream, no copying between streams, no encoding needed, just write the bytes! No need to over-complicate things with StreamReader if you already have a stream you can convert to bytes directly with. jpg file, though I admit I have only used it with small files (less than 1 MB). This code works as I've tested it with a. Using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.CreateNew, FileAccess.Write)) If path += (File.Exists(Path.Combine(path, fileName)))įile.Delete(Path.Combine(path, fileName)) String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) Once you have the bytes, you can easily write them to a file: public static void WriteFile(string fileName, byte bytes) I know some would like to force people to upgrade, but compatibility is also nice, too.Īnother thing, I don't get using a stream to copy from another stream in the first place. I don't get all of the answers using CopyTo, where maybe the systems using the app might not have been upgraded to. NET 4, serving basically the same purpose. Note that Stream.CopyTo was introduced in. To use it to dump a stream to a file, for example: using (Stream file = File.Create(filename)) While ( (len = input.Read(buffer, 0, buffer.Length)) > 0) Public static void CopyStream(Stream input, Stream output) / Copies the contents of input to output. if you do just want to copy one stream to another (e.g. Why do you need to use a StreamReader at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?ĮDIT: As this seems to be something people want to see. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?) You will almost certainly lose data if you use it for arbitrary binary data. You must not use StreamReader for binary files (like gifs or jpgs).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |