【发布时间】:2020-01-04 23:44:22
【问题描述】:
我正在编写一个备份实用程序。这是我的第一个 c# 表单应用程序。
对于大多数文件,FileInfo length() 与传递给 CopyFileEx 进度处理程序的 TotalFileSize 相匹配。但是,对于一个文件,我发现 FileInfo length() 小于传递给进度处理程序的 TotalFileSize。
程序使用 FileInfo 计算要复制的所有文件的总大小 它使用带有进度处理程序的 CopyFileEx 来复制文件。 进度处理程序用于更新要复制的所有数据的比例的进度条。
我的问题是有时复制的字节总数大于预期的总数。
我的调查表明,对于大多数文件,FileInfo length() 与传递给进度处理程序的 TotalFileSize 相匹配。但是,对于一个文件,FileInfo length() 小于传递给进度处理程序的 TotalFileSize。
为什么大小不同?如何使计算的总文件大小与复制的总字节数相匹配?
private UnsafeNativeMethods.CopyProgressResult localHandler(Int64 TotalFileSize, Int64 TotalBytesTransferred, Int64 StreamSize,
Int64 StreamBytesTransferred, UInt32 StreamNumber, UnsafeNativeMethods.CopyProgressCallbackReason CallbackReason, IntPtr SourceFile,
IntPtr DestinationFile, IntPtr Data)
{
switch (CallbackReason)
{
case UnsafeNativeMethods.CopyProgressCallbackReason.CallbackChunkedFinished:
Debug.Print("localHandler: TotalBytesTransferred={0} TotalFileSize={1} ", TotalBytesTransferred.ToString(), TotalFileSize.ToString());
break;
case UnsafeNativeMethods.CopyProgressCallbackReason.CallbackStreamSwitch:
break;
default:
break;
}
return UnsafeNativeMethods.CopyProgressResult.ProgressContinue;
}
private void ButtonTestFileSize_Click(object sender, EventArgs e)
{
bool success;
bool b=false;
string inputFile= @"C:\temp\WrongFileSize\myFile.conf";
string outputFile= @"C:\temp\WrongFileSize\myFile.con2";
/* Get the input Filename using FileInfo */
FileInfo file = new FileInfo(inputFile);
Debug.Print("input FileInfo.length={0}", file.Length);
string hres = UnsafeNativeMethods.HResultToString(UnsafeNativeMethods.GetHResult((uint)Marshal.GetLastWin32Error()));
success = UnsafeNativeMethods.CopyFileEx(inputFile,
outputFile,
new UnsafeNativeMethods.CopyProgressRoutine(localHandler),
IntPtr.Zero,
ref b,
CopyFileFlags.FileFailIfExists | CopyFileFlags.COPY_FILE_NO_BUFFERING);
if (!success)
{
Debug.Print("Failed");
}
else
{
Debug.Print("Success");
}
/* Get the output Filename using FileInfo */
file = new FileInfo(outputFile);
Debug.Print("outputFile FileInfo.length={0}", file.Length);
}
}
这段代码的输出如下:
input FileInfo.length=2636
localHandler: TotalBytesTransferred=2636 TotalFileSize=2662
localHandler: TotalBytesTransferred=2662 TotalFileSize=2662
Success
outputFile FileInfo.length=2636
【问题讨论】:
标签: c# file-copying fileinfo