【发布时间】:2017-04-09 12:49:49
【问题描述】:
我正在尝试写入一个文本文件,我的条件是如果该文件中已经存在写入,那么它应该打印“添加了另一行 - 消息”。所以我尝试了以下方法,但它抛出异常'它正在被另一个进程使用',我可以理解我做错了什么:
public void WriteMessage(string message)
{
string path = @"C:\Users\AT\Documents\Visual Studio 2013\Projects\Sample_App\Sample_App\app_data\log.txt"; //File path
FileStream stream;
if (File.Exists(path))
{
stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); //This section used to read and write operations
using (StreamWriter writer = new StreamWriter(stream)) //Writing words to the text file
{
string[] lines = File.ReadAllLines(path); //Here is the exception - It's being used by another process
if (lines.Length > 0)
{
writer.WriteLine("\n" + "Another Line Added - " + message);
writer.Flush();
stream.Close();
}
}
}
else
{
/**If text file is created for the first time - Starts**/
stream = new FileStream(path, FileMode.Create); //This section used to read and write operations
using (StreamWriter writer = new StreamWriter(stream)) //Writing words to the text file
{
writer.WriteLine(message);
writer.Flush();
stream.Close();
}
/**If text file is created for the first time - Ends**/
}
}
现在会发生什么情况,该文件是为第一个包含文本的 'Hello World!! 创建的,当我向其中添加另一个文本时,我期望得到以下输出:
预期输出:
世界你好!! ---- 只有第一次否则
添加了另一行 - Hello World!
添加了另一行 - Hello World!
添加了另一行 - Hello World!
我希望有一些想法或建议可以让它发挥作用,并让我知道我做错了什么。这完全是一个简单的。我想在文件中再做一件事,如下所示:
输出:
1) 你好世界!!
2) 你好世界!!
注意:在上面的输出中,每当我运行控制台应用程序时,我都会增加数字。这意味着如果存在相同的写入,那么它应该增加一。我期待一个简单的 Linq 能做到这一点,是否有可能以一种简单的方式做到:(在这种情况下,我是否需要创建任何模型来处理文本文件?)
var query = (var c in fileName
select c);
foreach(var item in query)
{
//Do something here
}
我已经完成了以下工作,但还无法完成上述工作:
【问题讨论】:
标签: c# text-files