C#, Creating .txt file

2020-02-15 03:22发布

I am having trouble creating a .txt file with the code below. I get an exception as follows:

Unhandled exception: System.unauthorizedAccessException: Access to the path 'C:\log.txt' is denied.

I have looked online and done similar things to what is on the api. Below is my code, so you can understand what my train of logic is. What do you think causes this exception? Thanks in advance!

static StreamWriter swt;
static string logFile = @"C:\log.txt";
static FileStream fs;
static void Main(string[] args)
{
    Console.Out.WriteLine(swt);
    string root =  args[0];                       
     if (!File.Exists(logFile))
     {
         try
         {
             fs = File.Create(logFile);
         }
         catch (Exception ex)
         {
             swt.WriteLine("EXCEPTION HAS BEEN THROWN:\n " + ex + "\n");
         }
         {

         }
     }
 }

标签: c# file
3条回答
\"骚年 ilove
2楼-- · 2020-02-15 03:40

Yes, it is permission error. You don't have enough rights to write file in C: drive. To write in these types of folder/drive you need admin permission.

You can give your application admin rights. Simple way is enforce your application to start in admin account/rights only. To achieve this

Solution Explorer -> your project -> Add new item (right click) -> Application Manifest File.

In this file change requestedExecutionLevel to

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

These enforce your application with admin rights only. On Windows 8/7/Vista it will display UAC (User Access Control) dialog box when you start the application.

Hope this will help you....

查看更多
成全新的幸福
3楼-- · 2020-02-15 03:44

Detect the folder permissions. It has to has write permission on the logged user.

查看更多
别忘想泡老子
4楼-- · 2020-02-15 03:47

You're most likely getting this error because a standard user cannot write to the root of a drive without elevated permissions. See here.

查看更多
登录 后发表回答