Radislav
Radislav

Reputation: 2983

How write MemoryStream data to file

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.

Upvotes: 0

Views: 16734

Answers (2)

user001
user001

Reputation: 415

I came across this error also and, like Jon Skeet suggests, the first issue was the access rights.

This was because I did not use a relative path to reach the destination folder. Once I changed this it allowed me to access and amend without trouble.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500065

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:

byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

you're assuming that you can get the length of the stream (not all streams support this), and you're also assuming that Read will 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 to f:\Test.txt to start with.

Upvotes: 8

Related Questions