2010-04-28 14 views
19

這兩種移動文件的方法是否有區別?FileInfo.MoveTo()vs File.Move()

System.IO.FileInfo f = new System.IO.FileInfo(@"c:\foo.txt"); 
f.MoveTo(@"c:\bar.txt"); 

//vs 

System.IO.File.Move(@"c:\foo.txt", @"c:\bar.txt"); 
+1

問題是什麼?他們似乎是兩種不同的方法來達到相同的API。你在尋找循環表現還是最佳做法? – jcolebrand 2010-04-28 21:34:32

+0

我只是好奇爲什麼有兩種方法看起來完全一樣。 – 2010-04-29 01:22:48

+0

希望下面的代碼片段告訴你它們有何不同?另外,如果您不使用Red Gate的(當前免費的)Reflector產品,您應該。 – jcolebrand 2010-04-29 14:32:09

回答

12

通過展鵬反射:

File.Move()

public static void Move(string sourceFileName, string destFileName) 
{ 
    if ((sourceFileName == null) || (destFileName == null)) 
    { 
     throw new ArgumentNullException((sourceFileName == null) ? "sourceFileName" : "destFileName", Environment.GetResourceString("ArgumentNull_FileName")); 
    } 
    if ((sourceFileName.Length == 0) || (destFileName.Length == 0)) 
    { 
     throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), (sourceFileName.Length == 0) ? "sourceFileName" : "destFileName"); 
    } 
    string fullPathInternal = Path.GetFullPathInternal(sourceFileName); 
    new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new string[] { fullPathInternal }, false, false).Demand(); 
    string dst = Path.GetFullPathInternal(destFileName); 
    new FileIOPermission(FileIOPermissionAccess.Write, new string[] { dst }, false, false).Demand(); 
    if (!InternalExists(fullPathInternal)) 
    { 
     __Error.WinIOError(2, fullPathInternal); 
    } 
    if (!Win32Native.MoveFile(fullPathInternal, dst)) 
    { 
     __Error.WinIOError(); 
    } 
} 

和FileInfo.MoveTo()

public void MoveTo(string destFileName) 
{ 
    if (destFileName == null) 
    { 
     throw new ArgumentNullException("destFileName"); 
    } 
    if (destFileName.Length == 0) 
    { 
     throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); 
    } 
    new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new string[] { base.FullPath }, false, false).Demand(); 
    string fullPathInternal = Path.GetFullPathInternal(destFileName); 
    new FileIOPermission(FileIOPermissionAccess.Write, new string[] { fullPathInternal }, false, false).Demand(); 
    if (!Win32Native.MoveFile(base.FullPath, fullPathInternal)) 
    { 
     __Error.WinIOError(); 
    } 
    base.FullPath = fullPathInternal; 
    base.OriginalPath = destFileName; 
    this._name = Path.GetFileName(fullPathInternal); 
    base._dataInitialised = -1; 
} 
3

唯一顯著區別我可以看到的是File.Move是靜態和FileInfo.MoveTo不是。
除此之外,它們運行的​​代碼大致相同。

+0

是的,我同意; FileInfo繼承FileSystemInfo而File只繼承Object。 FileSystemInfo顯然只給編組,所以我猜想FileInfo更容易管理。 – jcolebrand 2010-04-28 21:47:29

5

的一個重要區別同樣的解釋是,FileInfo.MoveTo()將更新FileInfo對象到目的地路徑的文件路徑。這顯然不是File.Move()的情況,因爲它只使用字符串作爲輸入。