如果文件不存在并插入新文本,我的代码可以正常工作,或者如果文件已经存在,则会重写当前内容。
path = @"C:\MY FOLDER\data.txt";
FileStream fileS = null;
bool done = false;
while (!done)
{
done = true;
try
{
FileStream fileStream = File.Open(path, FileMode.OpenOrCreate);
fileStream.SetLength(0);
fileStream.Close();
fileS = File.OpenWrite(path);
}
catch (IOException ex)
{
done = false;
// Thread.Sleep(3);
}
}
using (StreamWriter fs = new StreamWriter(fileS))
{
fs.Write(textA);
fs.Close();
};
fileS.Dispose();
现在我需要更改它,以便它不再重写内容,而是将新文本添加到以前的内容中。
其次,我需要知道文件是否完全为空,在这种情况下插入textA
或者是否已经有一些内容,在这种情况下添加textB
。
答案 0 :(得分:2)
试试这个
string path = @"Your File Path";
bool done = false;
while (!done)
{
done = true;
try
{
FileStream fileStream = null;
fileStream = File.Open(path, File.Exists(path) ? FileMode.Append : FileMode.OpenOrCreate);
using (StreamWriter fs = new StreamWriter(fileStream))
{
fs.WriteLine(fileStream.Length == 0 ? "Text A" : "Text B");
};
fileStream.Close();
}
catch (IOException)
{
done = false;
}
}
答案 1 :(得分:0)
你可以尝试类似的东西:
while (!done)
{
done = true;
try
{
FileStream fileStream;
if (File.Exists(path))
{
fileStream = File.Open(path, FileMode.Append);
}
else
{
fileStream = File.Open(path, FileMode.OpenOrCreate);
}
if (fileStream.Length == 0)
{
//write textA
}
else
{
//write textB
}
fileStream.Close();
}
catch (IOException ex)
{
done = false;
}
}
答案 2 :(得分:0)
你快到了!神奇的词是AppendText(string)
var path = @"C:\MY FOLDER\data.txt";
//Create the file if it doesn't exist
if (!File.Exists(path))
{
using (var sw = File.CreateText(path))
{
sw.WriteLine("Hello, I'm a new file!!");
// You don't need this as the using statement will close automatically, but it does improve readability
sw.Close();
}
}
using (var sw = File.AppendText(path))
{
for (int i = 0; i < 10; i++)
{
sw.WriteLine(string.Format("Line Number: {0}", i));
}
}
您不需要将sw.Close();
与using(StreamWriter){}
块一起使用,因为流会自动关闭,但它确实提高了可读性。
此外,当StreamWriter关闭时,它会同时自动Dispose()
(请参阅下面的代码段),因此不必自行调用Dispose()。
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
答案 3 :(得分:0)