C# 读取文本文件并用C进行更新#
我想读一个不断变化的文本文件 但第一个问题是文件太大,第一次挂起 这个文本文件(txt)的每一秒都在变化 不是第一次只调用文件的最后50行吗?所以程序没有停止C# 读取文本文件并用C进行更新#,c#,C#,我想读一个不断变化的文本文件 但第一个问题是文件太大,第一次挂起 这个文本文件(txt)的每一秒都在变化 不是第一次只调用文件的最后50行吗?所以程序没有停止 而且,它更容易阅读和添加不断变化的…对于文本文件的异步读取,请尝试使用文件帮助程序库 假设我正确理解了您的意思,我认为您应该不时重新打开该文件以从中读取,然后使用FileStream的Seek方法 见: 每次读取文件时,都应将文件存储到读取文件的位置。当您开始读取另一个块时,您可以使用seek方法使用该偏移量转到您尚未读取的文件部分 通过
而且,它更容易阅读和添加不断变化的…对于文本文件的异步读取,请尝试使用文件帮助程序库
假设我正确理解了您的意思,我认为您应该不时重新打开该文件以从中读取,然后使用FileStream的Seek方法 见: 每次读取文件时,都应将文件存储到读取文件的位置。当您开始读取另一个块时,您可以使用seek方法使用该偏移量转到您尚未读取的文件部分 通过这种方式,您可以分块读取文件,而不会将其锁定太长时间(从而阻止对其的写入操作) 然后,线程(或计时器对象)可以不时地从文件中读取。确保块不要太大,这样就不会锁定文件太长时间 您感兴趣的文件
static class Program
{
static long position = 0;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = System.Environment.CurrentDirectory;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "data.txt"; // or *.txt for all .txt files.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public static void OnChanged(object source, FileSystemEventArgs e)
{
using (FileStream fileStream = new FileStream("data.txt", FileMode.Open))
{
// Using Ron Deijkers answer, skip to the part you din't read.
fileStream.Seek(position, SeekOrigin.End);
for (int i = 0; i < fileStream.Length; i++)
{
fileStream.ReadByte();
}
}
}
}
静态类程序
{
静态长位置=0;
///
///应用程序的主要入口点。
///
[状态线程]
静态void Main()
{
FileSystemWatcher watcher=新的FileSystemWatcher();
watcher.Path=System.Environment.CurrentDirectory;
watcher.NotifyFilter=NotifyFilters.LastWrite;
watcher.Filter=“data.txt”;//或所有.txt文件的*.txt。
watcher.Changed+=新文件系统EventHandler(OnChanged);
watcher.EnableRaisingEvents=true;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(新Form1());
}
更改后的公共静态void(对象源、文件系统目标)
{
使用(FileStream FileStream=newfilestream(“data.txt”,FileMode.Open))
{
//使用Ron Deijkers的答案,跳到你没有读到的部分。
Seek(位置,SeekOrigin.End);
for(int i=0;i
这可能无法准确地演示您需要的程序流,但它确实提供了不会挂起UI的读写功能(异步)。希望你能适应你需要的东西
public class AsyncFileUpdate
{
object locker = new object();
public FileInfo File { get; private set; }
public AsyncFileUpdate(FileInfo file)
{
File = file;
}
/// <summary>
/// Reads contents of a file asynchronously.
/// </summary>
/// <returns>A task representing the asynchronous operation</returns>
public Task<string> ReadFileAsync()
{
return Task.Factory.StartNew<string>(() =>
{
lock (locker)
{
using (var fs = File.OpenRead())
{
StreamReader reader = new StreamReader(fs);
using (reader)
{
return reader.ReadToEnd();
}
}
}
});
}
/// <summary>
/// write file asynchronously
/// </summary>
/// <param name="content">string to write</param>
/// <returns>A task representing the asynchronous operation</returns>
public Task WriteFileAsync(string content)
{
return Task.Factory.StartNew(() =>
{
lock (locker)
{
using (var fs = File.OpenWrite())
{
StreamWriter writer = new StreamWriter(fs);
using (writer)
{
writer.Write(content);
writer.Flush();
}
}
}
});
}
}
/// <summary>
/// Demonstrates usage
/// </summary>
public class FileOperations
{
public void ProcessAndUpdateFile(FileInfo file)
{
AsyncFileUpdate fu = new AsyncFileUpdate(file); ;
fu.ReadFileAsync()
.ContinueWith(p => Process(p.Result))
.ContinueWith(p => fu.WriteFileAsync(p.Result));
}
/// <summary>
/// does the processing on the file content
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
string Process(string content)
{
throw new NotImplementedException("you do this bit ;)");
}
}
公共类异步文件更新
{
对象锁定器=新对象();
公共文件信息文件{get;private set;}
公共异步文件更新(文件信息文件)
{
文件=文件;
}
///
///异步读取文件的内容。
///
///表示异步操作的任务
公共任务ReadFileAsync()
{
返回Task.Factory.StartNew(()=>
{
锁(储物柜)
{
使用(var fs=File.OpenRead())
{
StreamReader=新的StreamReader(fs);
使用(读卡器)
{
返回reader.ReadToEnd();
}
}
}
});
}
///
///异步写入文件
///
///要写入的字符串
///表示异步操作的任务
公共任务WriteFileAsync(字符串内容)
{
返回Task.Factory.StartNew(()=>
{
锁(储物柜)
{
使用(var fs=File.OpenWrite())
{
StreamWriter writer=新StreamWriter(fs);
使用(编写器)
{
作者:写(内容);
writer.Flush();
}
}
}
});
}
}
///
///演示用法
///
公共类文件操作
{
public void ProcessAndUpdateFile(FileInfo文件)
{
AsyncFileUpdate fu=新的AsyncFileUpdate(文件);
fu.ReadFileAsync()
.ContinueWith(p=>Process(p.Result))
.ContinueWith(p=>fu.WriteFileAsync(p.Result));
}
///
///是否对文件内容进行处理
///
///
///
字符串进程(字符串内容)
{
抛出新的NotImplementedException(“您做了这一点;)”;
}
}
所有这些Task
业务都来自taskparallel库,这是一个很好的工具包,可以帮助您摆脱并行和异步编程
注意:文件系统访问非常昂贵,而且会降低存储介质的物理性能。您是否控制此文件(是否创建此文件)?每秒更新一个文件是非常禁止的。如果您在检查文件时担心文件更改,可能需要先复制一份文件?在文件更改时,我认为没有可靠的方法读取文件…读取更改的文件需要使用某种只读选项,以便在使用文件时不锁定文件。同样,您需要能够对其进行写入—如果它是一个日志文件,则任何正在写入日志的应用程序都可能正在使用它,并且您可能缺少更改权限。最后,您的问题还不清楚-您想如何修改该文件?我相信他的意思是他正在阅读一个大文件。数据只添加到文件的末尾。他第一次加载文件需要很长时间,然后他的程序在读取时挂起一段时间。在那之后,我想他只想看文件的结尾。顺便说一句,这是一个令人震惊的模棱两可的问题。考虑再详细一些,这是否同时解决了读写时的同步问题?如果是这样的话,也许可以给我们一个样本。这次行动毫无意义