PathTooLongException in C# code

yeahumok picture yeahumok · Jul 6, 2009 · Viewed 8.6k times · Source

i have the following code:

 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");


        }

I keep hitting a PathTooLongException error with the following line:

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

The application drills into a drive and finds all files/folders w/in the drive. I cannot change this path but since it is above 260 characters...how to work around this?

Answer

LBushkin picture LBushkin · Jul 6, 2009

The GetLastAccessTime() call, with a full path can exceed the internal limit (which is OS-version specific, but typically 260 characters) on the maximum length for a fully qualified file path.

One way to avoid this, is to use Directory.SetCurrentDirectory() to change the current system directory and then call GetLastAccessTime() with only a relative path. Just make sure you change your current directory back to what you started from to avoid unexpected issues.