C# 文件操作不会替换整行
我正在尝试用另一行替换文件行 这是我的代码块C# 文件操作不会替换整行,c#,.net,io,C#,.net,Io,我正在尝试用另一行替换文件行 这是我的代码块 string text = readWholeFile(fileName); text = text.Replace(oldLine, newLine); IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication(); using (var isoFileStream = new IsolatedStorageFileStream(fileName,
string text = readWholeFile(fileName);
text = text.Replace(oldLine, newLine);
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
using (var isoFileStream = new IsolatedStorageFileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write, myStore))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.WriteLine(text);
isoFileWriter.Close();
}
isoFileStream.Close();
问题是,换行符只替换换行符的确切数目。例如,如果OldLine是1234567890
,而换行符是asd
。文件操作提供如下输出
asd
4567890
这里
readWholeFile
方法读取整个文件。和oldLine
,newLine
是方法字符串参数。这段代码按预期工作:
string text = "1234567890\n1234567891\n1234567892";
var rText = text.Replace("1234567890", "asd");
Console.WriteLine(rText);
Console.ReadKey();
输出为:
asd
1234567891
1234567892
很明显,问题不在于String.Replace方法。
您可以使用一个简单的代码“读取整个文件”:
然后呢,
var rText = str.ToString().Replace(oldLine, newLine);
最后,再次将所有内容保存到文件:
File.WriteAllText(outputFile, rText);
编辑
此外,以下代码也起作用:
string text = "1234567890\n1234567891\n1234567892";
var rText = text.ToString().Replace("1234567890", "asd");
using (var isoFileStream = new FileStream("output.txt",
FileMode.Create, FileAccess.Write))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.Write(rText);
}
}
正如预期的那样,产出是:
asd
1234567891
1234567892
但我发现以下问题:
using (var isoFileStream = new FileStream("output.txt",
FileMode.OpenOrCreate, FileAccess.Write))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.Write(rText);
}
}
造成问题的情况是,该文件已存在,且包含以下内容:
1234567890
1234567891
1234567892
文件中的输出为:
asd
1234567891
1234567892
67892
如果将文件模式改为File.Create而不是File.open或Create,则问题消失
编辑
我没有使用“IsolatedStorageFile”,只是因为我没有在SilverLight上下文上进行测试,也没有使用ClickOnce进行部署,因此它无法工作我不确定您是否向我们展示了整个情况。您的数据中的回车很有趣。我认为您的示例数据与您的输出示例不匹配。输出中的回车是可疑的。能否显示readWholeFile方法?顺便说一句,当filestream或streamwriter处于using语句中时,您不需要关闭它。我用Replace测试了一个更简单的代码,它按预期工作。@paqogomez,输出中的回车符在那里,因为他正在使用WriteLine写入,并且输出文件存在并且不是空的。我怀疑,在第一次尝试时,他将原始字符串写入其中,后来更改为替换的字符串,但随后该文件不再是空的,只是作为旁注:Silverlight不是唯一可以使用IsolatedStorage的地方,桌面和Windows应用商店应用程序也可以使用它。
asd
1234567891
1234567892
67892