這兩種移動文件的方法是否有區別?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");
這兩種移動文件的方法是否有區別?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");
採取這個MSDN網頁http://msdn.microsoft.com/en-us/library/akth6b1k.aspx看看「備註」部分:
如果你打算重用的對象幾次,可以考慮使用的FileInfo,而不是相應的靜態方法的實例方法文件類,因爲安全檢查並不總是必要的。
這種差異在File(Directory)和FileInfo(DirectoryInfo)類之間是最重要的。
通過展鵬反射:
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;
}
唯一顯著區別我可以看到的是File.Move
是靜態和FileInfo.MoveTo
不是。
除此之外,它們運行的代碼大致相同。
是的,我同意; FileInfo繼承FileSystemInfo而File只繼承Object。 FileSystemInfo顯然只給編組,所以我猜想FileInfo更容易管理。 – jcolebrand 2010-04-28 21:47:29
的一個重要區別同樣的解釋是,FileInfo.MoveTo()將更新FileInfo對象到目的地路徑的文件路徑。這顯然不是File.Move()的情況,因爲它只使用字符串作爲輸入。
問題是什麼?他們似乎是兩種不同的方法來達到相同的API。你在尋找循環表現還是最佳做法? – jcolebrand 2010-04-28 21:34:32
我只是好奇爲什麼有兩種方法看起來完全一樣。 – 2010-04-29 01:22:48
希望下面的代碼片段告訴你它們有何不同?另外,如果您不使用Red Gate的(當前免費的)Reflector產品,您應該。 – jcolebrand 2010-04-29 14:32:09