9

Currently developing a C# WinForms application in Visual Studio 2010 .NET 4 on Windows 7.

Firstly I am reading a stream of bytes from a file using the File.ReadAllBytes() method. Then when attempting to write the file back, I am getting a access to path denied error when using the WriteAllBytes method.

I have tried passing in literal paths, Environment.SpecialFolder.ApplicationData, Path.GetTempPath(), but all are providing me with the same error.

I have checked permissions on these folders and also attempted to start the program in administrator mode with no luck.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1097734
  • 163
  • 1
  • 3
  • 10

3 Answers3

14

Make sure that you specify the entire path when using File.WriteAllBytes() including file name.

File.WriteAllBytes() cannot write to a general directory, it has to write to a specific file.

Hope this helps.

Vasilis
  • 2,721
  • 7
  • 33
  • 54
VentingOlive
  • 151
  • 1
  • 5
4

In windows7 there are security issues on c:. If you modified the path to D: then no access denied issue will be there.

Try following sample code with Path.GetTempPath(), it will execute successfully.

    static void Main(string[] args)
    {
        string path = Path.GetTempPath();
        byte[] binaryData;
        string text = "romil123456";
        using (MemoryStream memStream = new MemoryStream(Encoding.ASCII.GetBytes(text)))
            {
                binaryData = memStream.ToArray();
            }
            System.IO.File.WriteAllBytes(@path + "\\words123.txt"    , binaryData);
        }
    }

Environment.SpecialFolder.ApplicationData provides the folder name, not provides the full path to that folder. so when you use this in path defined to write file, this folder is searched under in local application path.

Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92
2

Are you sure the file isn't still locked? If you are planning to read + write bytes from a file, you might want to consider using a Stream class (for example the FileStream), the advantage is that you will lock the file and that no other application can access the file in the meantime.

Code example from this topic:

FileStream fileStream = new FileStream(
  @"c:\words.txt", FileMode.OpenOrCreate, 
  FileAccess.ReadWrite, FileShare.None);
Community
  • 1
  • 1
Styxxy
  • 7,462
  • 3
  • 40
  • 45