I have this code:
private void SaveStreamToFile(string fileFullPath, Stream stream)
{
if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a file
using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
{
// Fill the bytes[] array with the stream data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
I call this method like this SaveStreamToFile(@”f:\Test.txt”, memoryStream);
I got error:File operation not permitted. Access to path ‘f:\Test.txt’ is denied.
Well, presumably that means you don’t have write access to
f:\Test.txt. That’s a problem outside the scope of .NET, really.However, your method is broken. Here:
you’re assuming that you can get the length of the stream (not all streams support this), and you’re also assuming that
Readwill read the whole thing in one go. That’s not necessarily the case.If you’re using .NET 4, you can use
Stream.CopyTo, which will make life a lot simpler. (Although that won’t help you to abort if there’s no data in the stream.) But you’ll still need to fix the inability to write tof:\Test.txtto start with.