The simple solution is would be to use a unc enabled path which will would allow file paths of up to approx 32767 chars
string longPathEnabledFileName = Path.ToLongPath("C:\SomeVeryLongPath\....");
FileStream fs = new FileStream(longPathEnabledFileName);
This would simply prepend the path with \\?\ which tells the framework to bypass the MAX_PATH limitation of 260 chars. Unfortunately, The prefix of \\?\ is not supported within .Net at the time of writing (as of version 4.0)
This leaves us with a WinApi solution and reference Kernel32.dll to use the SafeFileHandle. Kim Hamilton from the BCL team has blogged a series of workarounds to the MAX_PATH limitations here of (Part 2 shows how to use the winapi functions) with a code snippet included here for reference:
// This code snippet is provided under the Microsoft Permissive License.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeFileHandle CreateFile(
string lpFileName,
EFileAccess dwDesiredAccess,
EFileShare dwShareMode,
IntPtr lpSecurityAttributes,
ECreationDisposition dwCreationDisposition,
EFileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
public static void TestCreateAndWrite(string fileName) {
string formattedName = @"\\?\" + fileName;
// Create a file with generic write access
SafeFileHandle fileHandle = CreateFile(formattedName,
EFileAccess.GenericWrite, EFileShare.None, IntPtr.Zero,
ECreationDisposition.CreateAlways, 0, IntPtr.Zero);
// Check for errors
int lastWin32Error = Marshal.GetLastWin32Error();
if (fileHandle.IsInvalid) {
throw new System.ComponentModel.Win32Exception(lastWin32Error);
}
// Pass the file handle to FileStream. FileStream will close the
// handle
using (FileStream fs = new FileStream(fileHandle,
FileAccess.Write)) {
fs.WriteByte(80);
fs.WriteByte(81);
fs.WriteByte(83);
fs.WriteByte(84);
}
}
There is also a library that encapsulates all this work over at google code called zeta long paths