C# – Need to use win32 api to copy files in c# – how to do this


I'm trying to copy some files around, and occasionally the lengths of the names exceeds the length that the System.IO.File.Copy method can accept (260 chars according to the exception that is getting thrown)

According to the research I've done, I should be able to use the win32 api's file methods in conjunction with \?\ prepended to paths to get a 32,000 character limit, but I'm not sure witch methods I need to import.

Can someone help me with this? I'm looking for something like (obviously a different function, but you get the idea):

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern SafeFileHandle CreateFileW(string lpFileName, uint dwDesiredAccess,
                                          uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
                                          uint dwFlagsAndAttributes, IntPtr hTemplateFile);

Best Solution

           CharSet = CharSet.Unicode,
           CallingConvention = CallingConvention.StdCall,
           SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFile(
                   [MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName,
                   [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName,
                   [MarshalAs(UnmanagedType.Bool)] bool bFailIfExists);