Why is access to the path denied?

前端 未结 29 1514
刺人心
刺人心 2020-11-22 15:25

I am having a problem where I am trying to delete my file but I get an exception.

if (result == \"Success\")
{
     if (FileUpload.HasFile)
     {
         t         


        
29条回答
  •  天涯浪人
    2020-11-22 15:55

    To solve this problem, I follow the Scot Hanselman approach at Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied) article, the code with example is bellow:

    class Program
    {
        static void Main(string[] args)
        {
            var path = "c:\\temp\\notfound.txt";
            try
            {
                File.Delete(path);
            }
            catch (UnauthorizedAccessException)
            {
                FileAttributes attributes = File.GetAttributes(path);
                if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    attributes &= ~FileAttributes.ReadOnly;
                    File.SetAttributes(path, attributes);
                    File.Delete(path);
                }
                else
                {
                    throw;
                }
            }
        }
    }
    

提交回复
热议问题