gpt4 book ai didi

c# - 文件系统观察器和大文件

转载 作者:可可西里 更新时间:2023-11-01 08:15:24 26 4
gpt4 key购买 nike

var fsw = new FileSystemWatcher(sPath, "*.PPF");
fsw.NotifyFilter = NotifyFilters.FileName;
fsw.IncludeSubdirectories = true;
fsw.Created += FswCreated;
fsw.EnableRaisingEvents = true;

static void FswCreated(object sender, FileSystemEventArgs e)
{
string sFile = e.FullPath;
string[] arrLines = File.ReadAllLines(sFile);
}

对于大文件这会失败,因为写入文件的过程还没有完成。该文件是通过网络复制的,所以我不知道文件的大小。需要什么样的同步才能使其健壮?

最佳答案

在stackoverflow上找到的解决方案,稍微修改了一下。

static 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;
}

static void FswCreated(object sender, FileSystemEventArgs e)
{
string sFile = e.FullPath;

Console.WriteLine("processing file : " + sFile);

// Wait if file is still open
FileInfo fileInfo = new FileInfo(sFile);
while(IsFileLocked(fileInfo))
{
Thread.Sleep(500);
}

string[] arrLines = File.ReadAllLines(sFile);
}

关于c# - 文件系统观察器和大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3822175/

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