Search code examples
c#.netsystem.io.filesystem.io.directory

File could not be found using long file Paths


I'm trying to remove the lfs tracking tag from git before I process some files only some of the files when used in our companies jenkins server contain file paths that are 260+ characters. Due to this I am trying to get C# to work with long file paths. I seem to be struggling with the below code I get "Could not find file" however I 100% no the file exists and think i'm doing something incorrect in terms of my use of @"\?\" Any advice would be appreciated.

    static int removeLFSTracking(string path)
    {
        int rC = STATUS_OK;
        string lfsTracked = ".lfs.tracked";

        List<string> files = new List<string>();
        getFiles( path, files );

        foreach(string file in files)
        {
            if(file.Contains(lfsTracked))
            {
                string newFileName = file.Replace(lfsTracked, "");
                try
                {
                    System.IO.File.Move( @"\\?\" + file, @"\\?\" + newFileName );
                }
                catch(SystemException e)
                {
                    Console.WriteLine( "Failed to remove lfs tracked from file " + file );
                    Console.WriteLine( e.ToString( ) );
                }
            }
        }
        return rC;
    }

my XML app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
  <configSections>
    <section name="Extensions" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </configSections>
  <runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
  </runtime>
   <startup> 
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>

Answer was: I was using relative paths, this doesn't seem to work with the syntax and when I changed to absolute paths my code worked fine.


Solution

  • I was using relative Paths for file and newFileName, these didn't work in conjunction with the \?\ syntax, once I changed these to absolute it worked fine.