How to fix Access to the path '...' is denied. error in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • belohlavek
    New Member
    • Jun 2012
    • 1

    How to fix Access to the path '...' is denied. error in C#

    I'm on windows 7 creating a desktop aplication in Visual C# 2010.
    The error's produced here:

    Code:
    void Copymove(string file) 
    {
     File.Copy(Environment.GetFolderPath(Environment.SpecialFold er.MyDocuments), "../../contenidos/" + file);
    }
    The exact error:
    Access to the path 'C:\Users\Danie l\Documents' is denied.

    I've already tried modifying the app.manifest and it does not work... It's been about 4 hours i've been trying to fix this. Any ideas?

    Thanks in advance.
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    Firstly your trying to copy the entire My Documents folder into a file, that can't be done like that, File.Copy(..) is used to copy a single file, so make sure the parameters are correct.

    Secondly Windows 7 is picky with how you access files, and for the most part will deny access to anything on the primary drive it deems important.

    Here is method that you can use that manually copies a file, hopefully this will help show how the File.Copy method works, remember to always pass a full filename in for fileFrom and fileTo:

    Code:
    void FileCopy(string fileFrom, string fileTo, long bufferSize = 1024)
    {
        byte[] buffer = new byte[bufferSize];
        using (FileStream inStream = new FileStream(fileFrom, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            using (FileStream outStream = new FileStream(fileTo, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                while (inStream.Position < inStream.Length - buffer.Length)
                {
                    inStream.Read(buffer, 0, buffer.Length);
                    outStream.Write(buffer, 0, buffer.Length);
                }
    
                // Copy the remaining part.
                buffer = new byte[inStream.Length - inStream.Position];
                inStream.Read(buffer, 0, buffer.Length);
                outStream.Write(buffer, 0, buffer.Length);
            }
        }
    }
    example usage:

    Code:
    string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string fileIn = Path.Combine(myDocs, "stuff.txt");
    string fileOut = "e:\\stuff.txt";
    FileCopy(fileIn, fileOut);
    Aimee.

    Comment

    Working...