gpt4 book ai didi

c# - 等到文件完全写入

转载 作者:IT王子 更新时间:2023-10-29 03:44:10 26 4
gpt4 key购买 nike

在一个目录中创建文件 (FileSystemWatcher_Created) 时,我将其复制到另一个目录。但是当我创建一个大文件(> 10MB)时它无法复制文件,因为它已经开始复制,当文件尚未完成创建时...
这会导致 Cannot copy the file, because it's used by another process 被引发。 ;(
有帮助吗?

class Program
{
static void Main(string[] args)
{
string path = @"D:\levan\FolderListenerTest\ListenedFolder";
FileSystemWatcher listener;
listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;

while (Console.ReadLine() != "exit") ;
}

public static void listener_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine
(
"File Created:\n"
+ "ChangeType: " + e.ChangeType
+ "\nName: " + e.Name
+ "\nFullPath: " + e.FullPath
);
File.Copy(e.FullPath, @"D:\levan\FolderListenerTest\CopiedFilesFolder\" + e.Name);
Console.Read();
}
}

最佳答案

您面临的问题只有解决方法。

在开始复制过程之前检查文件ID是否在进程中。您可以调用以下函数,直到获得 False 值。

第一种方法,直接复制自this answer :

private bool IsFileLocked(FileInfo file)
{
FileStream stream = null;

try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}

//file is not locked
return false;
}

第二种方法:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
//check that problem is not in destination file
if (File.Exists(file) == true)
{
FileStream stream = null;
try
{
stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex2)
{
//_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
{
return true;
}
}
finally
{
if (stream != null)
stream.Close();
}
}
return false;
}

关于c# - 等到文件完全写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10982104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com