tags:

views:

441

answers:

3

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?

A: 

.NET doesn't support Unicode file paths, so the only option I know of in this case is using P/Invoke (unless, of course, you can change the path) to call Win32 API functions that do support them. You can look here for instructions on how to use Unicode file path to break the 260 characters barrier.

On Freund
A: 

As Microsoft says here, there is a Windows limitation on 260 characters.

You can try to avoid this with a symbolic link (not sure...).

FerranB
The link with the limitation actually contains the solution (see my answer to the question).
On Freund
+3  A: 

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.

LBushkin
I reached this response researching for a similar issue. But I find that SetCurrentDirectory also throws PathTooLongExceptipn. My question is at http://stackoverflow.com/questions/4050199/directory-setcurrentdirectory-throws-pathtoolongexception. Appreciate any comments you have.
Hemal Pandya
@Hemal: `SetCurrentDirectory()` accepts relative paths. Have you tried splitting the operation into two calls? So, for example to navigate to `C:\FirstPart\SecondPart\ThirdPart` you would do: `SetCurrentDirectory("C:\\FirstPart\\SecondPart"); SetCurrentDirectory(".\\ThirdPart");`. By splitting the directory navigation into multiple steps you may be able to sidestep the path length limitations.
LBushkin
@LBushkin thanks for responding. Yes, I tried relative paths but that also gives the same exception when I reach the length limit.
Hemal Pandya