簡體   English   中英

C# 為什么我的代碼會拋出 io.system.directorynotfound?

[英]C# Why is my code throwing a io.system.directorynotfound?

為什么下面的代碼會拋出 io.system.directorynotfound 異常? 我自己無法重現問題,但我的代碼的另一個用戶確實看到了它,有什么想法嗎? 謝謝

try
{
  //create path
  string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
  //check path exists
  if (!System.IO.File.Exists(strAppData))
  {
      System.IO.Directory.CreateDirectory(strAppData);
  }
  System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
  int count = dir.GetFiles().Length;

  if (count > 100)
  {
      string[] files = System.IO.Directory.GetFiles(strAppData);

      foreach (string file in files)
      {
          System.IO.File.Delete(file);
      }
  }


  this.fileName = fileName;
  // delete the file if it exists
  if (File.Exists(fileName))
  {
      //delete the file
      File.Delete(fileName);
  }

      // write the data to the file
      fs = File.OpenWrite(fileName);
      sWriter = new StreamWriter(fs);

      sWriter.WriteLine(headerText);

      sWriter.Flush();
      sWriter.Close();
}
catch (Exception exp)
{
    throw new Exception(exp.Message);
}

在檢查路徑是否存在時,您是否嘗試過使用 System.IO.Directory.Exists 而不是 System.IO.File.Exists?

您正在使用System.IO.File而不是System.IO.Directory檢查目錄是否存在。 它可能適用於您的機器,因為該目錄已經存在,因此檢查無關緊要。

無論哪種方式,您都需要記住文件系統是易失的。 與其檢查是否存在,不如嘗試打開資源並在失敗時處理異常。

檢查目錄是否存在,而不是文件...

盡管您正在檢查它,並在它不存在時創建它。 您不知道他們是否有創建目錄的權限。 因此,您的 Directory.CreateDirectory 調用也可能失敗,然后代碼的 rest 將失敗

http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

“評論

Exists 方法不應用於路徑驗證,該方法僅檢查路徑中指定的文件是否存在。 將無效路徑傳遞給 Existsl 將返回 false。 "

那是你的錯誤。 您的驗證不能確保文件的路徑存在

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM