user712923
user712923

Reputation: 1555

Writing to a file I get unauthorized access error.How can I do it?

Despite numerous post on the web I cannot find an answer to my problem. I am writing an application that writes csv files to folders.Users should be able to pick a directory. I am developing in windows 7 using vs2010 running my app in Admin Mode.Regardless of all this I still get the "Unauthorized access exception" when I do

   var path=@"c:\" or c:\MyFolder
   StringBuilder sb=new StringBuilder();
   sb.AppendLine("Test");
   var myFile=sb.ToString();
   using (var writer=new StreamWriter(path))
     {
        writer.Write(myFile);
     }

Am I missing something? I have feeling that in window7 you can only write to designated folders.Is this what's happening?

any suggestions?

EDITED

I have created few folders under "C:\MyFolder\"

I am not using any credentials eg windows impersonation etc..

It does write if it writes to the bin\debug\ of my class library. but not to any designated folder.

Upvotes: 3

Views: 6704

Answers (2)

Chris Dickson
Chris Dickson

Reputation: 12135

Is your code snippet the real code causing the problem?

On the face of it, you are trying to stream the text "Test" into a directory on the file system, not trying to write a file. (path is just assigned to @"C:\"). I'm not surprised that you get an UnauthorizedAccessException.

Assign the full path of the file you want to write into your path variable, and I imagine you'll succeed.

Upvotes: 7

Don Rolling
Don Rolling

Reputation: 2339

Try running your app with "Run as Administrator". The comments above will probably also steer you in the right direction. You should definitely pick a directory that your windows users has access to edit.

Upvotes: 0

Related Questions