2009-07-06 34 views
2

我有以下代碼:PathTooLongException在C#代碼

public static void Serialize() 
    { 

     List<string> dirs = FileHelper.GetFilesRecursive(fileDirectoryPath); 
     List<string> dirFiles = new List<string>(); 
     foreach (string p in dirs) 
     { 
      string path = p; 

      string lastAccessTime = File.GetLastAccessTime(path).ToString(); 


      bool DirFile = File.Exists(path); 
      FileInfo fInf = new FileInfo(path); 
      long lengthInk = fInf.Length/1024; 

      DateTime lastWriteTime = File.GetLastWriteTime(p); 
      dirFiles.Add(p + "|" + lastAccessTime.ToString() + "|" + DirFile.ToString() + "|" + lastWriteTime.ToString() + "|" + lengthInk.ToString() + " kb"); 


     } 

我不斷撞擊與以下行PathTooLongException錯誤:

string lastAccessTime = File.GetLastAccessTime(path).ToString(); 

應用鑽入一個驅動器,並找到所有文件/文件夾w /在驅動器中。我無法改變這條道路,但因爲它超過了260個字符......如何解決這個問題?

+0

use windows api [http://galratner.com/blogs/net/archive/2011/02/13/getting-around-pathtoolongexception-on-file-move-with-windows-native-api.aspx ](http://galratner.com/blogs/net/archive/2011/02/13/getting-around-pathtoolongexception-on-file-move-with-windows-native-api.aspx) – julian 2012-02-06 14:53:35

+0

我自己的和其他答案[here](http://stackoverflow.com/a/29605805/589059)建議您可以使用一些包裝庫來處理長路徑。 – rkagerer 2015-04-13 13:32:07

+0

可能重複的[如何避免System.IO.PathTooLongException?](http://stackoverflow.com/questions/530109/how-to-avoid-system-io-pathtoolongexception) – Deantwo 2017-03-14 12:42:49

回答

4

帶有完整路徑的GetLastAccessTime()調用可以在完全限定文件路徑的最大長度上調用exceed the internal limit(這是OS版本特定的,但通常爲260個字符)。

避免這種情況的一種方法是使用Directory.SetCurrentDirectory()來更改當前的系統目錄,然後只用相對路徑調用GetLastAccessTime()。只要確保將當前目錄更改回到開始的目錄,以避免出現意外問題。

0

.NET不支持Unicode文件路徑,所以我知道在這種情況下唯一的選擇是使用P/Invoke(當然,除非你可以改變路徑)來調用支持它們的Win32 API函數。您可以查看here以獲取有關如何使用Unicode文件路徑打破260個字符障礙的說明。

0

正如微軟所說的here,260個字符有Windows限制。

您可以嘗試使用symbolic link(不確定...)來避免這種情況。

+0

帶限制的鏈接實際上包含解決方案(請參閱我對問題的回答)。 – 2009-07-06 15:26:32

2

類似於Delimon.Win32.IO.FileInfo的.LastAccessTime屬性,可能會訣竅。

Delimon是克服長文件名問題上的Microsoft TechNet庫,這就是所謂的Delimon.Win32.I​O Library (V4.0),它有自己的重點班的版本從System.IO

例如,你將取代:

System.IO.Directory.GetFiles 

Delimon.Win32.IO.Directory.GetFiles 

這將讓你處理長文件和折ERS。

從網站:

Delimon.Win32.IO取代System.IO和 支持的基本文件功能文件&文件夾名最多可達32,767個字符。

此庫是在.NET Framework 4.0上編寫的,可以在x86 & x64系統上使用 。文件&標準 System.IO名稱空間的文件夾限制可以使用文件名中包含260個字符且文件名爲 ,文件夾名稱中包含240個字符的文件(MAX_PATH通常爲 配置爲260個字符)。通常,您會遇到標準.NET庫的 System.IO.PathTooLongException錯誤。