从程序的多个实例向文件写入文本 [英] Writing text to file from multiple instances of program

查看:157
本文介绍了从程序的多个实例向文件写入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写信息,以文件和程序的多个副本runnnig我得到这个错误:

When I write info to file and multiple copies of program are runnnig I get this error:

该进程无法访问该文件' C:因为它正被另一个进程使用\logs\log.txt

The process cannot access the file 'C:\logs\log.txt' because it is being used by another process.

代码是:

// create a writer and open the file
TextWriter tw2 = File.AppendText(@"C:\logs\log.txt");

// write a line of text to the file
tw2.WriteLine(Environment.NewLine);
tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER");
tw2.Flush();



如何做到在正确的方式?

How to do it in right way?

推荐答案

始终封装这种代码在使用语句

Always encapsulate this kind of code in a using statement

using(TextWriter tw2 = File.AppendText(@"C:\logs\log.txt"))
{
    tw2.WriteLine(Environment.NewLine); 
    tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER"); 
    //tw2.Flush();  // No need to flush because close alway flush.
}



使用语句在块的末尾调用tw2.Close()。结果
同时,如果你得到的异常而块中。

The using statement calls tw2.Close() at the end of the block.
Also if you get exceptions while inside the block.

现在,如果你的应用程序的其他实例由于某种原因失败,该文件没有更多的锁定

Now if the other instances of your application fails for some reason, the file is no more locked

这篇关于从程序的多个实例向文件写入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆