c# - Vérifiez si un fichier est réel ou un lien symbolique

Mots clés : c#symlinkc#

meilleur 3 Réponses c# - Vérifiez si un fichier est réel ou un lien symbolique

vote vote

91

private bool IsSymbolic(string path) {     FileInfo pathInfo = new FileInfo(path);     return pathInfo.Attributes.HasFlag(FileAttributes.ReparsePoint); } 
vote vote

83

private static SafeFileHandle getFileHandle(string path) {     return CreateFile(path, genericReadAccess, shareModeAll, IntPtr.Zero, openExisting,         fileFlagsForOpenReparsePointAndBackupSemantics, IntPtr.Zero); }  public static string GetTarget(string path) {     SymbolicLinkReparseData reparseDataBuffer;      using (SafeFileHandle fileHandle = getFileHandle(path))     {         if (fileHandle.IsInvalid)         {             Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());         }          int outBufferSize = Marshal.SizeOf(typeof(SymbolicLinkReparseData));         IntPtr outBuffer = IntPtr.Zero;         try         {             outBuffer = Marshal.AllocHGlobal(outBufferSize);             int bytesReturned;             bool success = DeviceIoControl(                 fileHandle.DangerousGetHandle(), ioctlCommandGetReparsePoint, IntPtr.Zero, 0,                 outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);              fileHandle.Close();              if (!success)             {                 if (((uint)Marshal.GetHRForLastWin32Error()) == pathNotAReparsePointError)                 {                     return null;                 }                 Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());             }              reparseDataBuffer = (SymbolicLinkReparseData)Marshal.PtrToStructure(                 outBuffer, typeof(SymbolicLinkReparseData));         }         finally         {             Marshal.FreeHGlobal(outBuffer);         }     }     if (reparseDataBuffer.ReparseTag != symLinkTag)     {         return null;     }      string target = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,         reparseDataBuffer.PrintNameOffset, reparseDataBuffer.PrintNameLength);      return target; } 
vote vote

78

static void Main( string[] args ) { FileInfo file_info = new FileInfo(args[0]); DirectoryInfo directory_info = new DirectoryInfo(args[0]);  bool is_file = file_info.Exists; bool is_directory = directory_info.Exists;  if (is_file) {     Console.WriteLine(file_info.ToString() + " is a file");      if ( file_info.Attributes.HasFlag(FileAttributes.ReparsePoint) )         Console.WriteLine(args[0] + " is a Windows file link"); } else if (is_directory) {     Console.WriteLine(directory_info.ToString() + " is a directory");      if ( directory_info.Attributes.HasFlag(FileAttributes.ReparsePoint) )         Console.WriteLine(args[0] + " is a Windows directory link"); } 

Questions similaires