System.UnauthorizedAccessException while creating a file

后端 未结 3 763
遥遥无期
遥遥无期 2021-01-18 14:26

I was trying to write a code so that I could log the error messages. I am trying to name the file with the date and would like to create a new log file for each day. After g

3条回答
  •  耶瑟儿~
    2021-01-18 14:49

    Your path is strange : "My documents" directory must be "C:\Users\MyName\Documents\"

    You can use Environment in order to correct it easily :

    String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    

    Note that it will acces to "My documents" folder of the user that running your exe.

    Second error, CreateDirectory must have a path in argument, not a file. using like you do will create a sub-directory with the file name. So you can't create a file with this name !

    Try this :

    String fileName = DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);
    
    String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        + @"\visual studio 2012\projects\training\discussionboard\ErrorLog\";
    String fileFullName = filePath + fileName + ".txt";
    
        if (File.Exists(fileFullName ))
        {
            File.WriteAllText(fileFullName , error);
        }
        else
        {
            Directory.CreateDirectory(filePath);
    
    [...]
        }
    }
    

提交回复
热议问题