【问题标题】:File Operation does not replace whole line文件操作不替换整行
【发布时间】:2014-12-11 18:14:43
【问题描述】:

我正在尝试用另一行替换文件行。

这是我的代码块

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();

问题在于 Line 只替换了 newLine 字符的确切数量。例如,如果 OldLine 是 1234567890 而 newLine 是 asd。文件操作给出类似这样的输出

asd
4567890

这里readWholeFile 方法读取整个文件。而oldLine,newLine是方法字符串参数。

【问题讨论】:

  • 我不确定您是否向我们展示了全貌。 Clearly your replace method replaces the whole string。您的数据中的回车很有趣。我认为您的示例数据与您的输出示例不匹配。输出中的回车是可疑的。
  • 你能显示 readWholeFile 方法吗?在旁注中,当您在 using 语句中使用文件流或流写入器时,您不需要关闭它
  • 我用 Replace 测试了一个更简单的代码,它按预期工作。
  • @paqogomez,输出中有回车,因为他正在使用 WriteLine 写入,并且输出文件存在且不为空。我怀疑在第一次尝试中他将原始字符串写入其中,后来更改为替换,但随后文件不再为空

标签: c# .net io


【解决方案1】:

这段代码按预期工作:

string text = "1234567890\n1234567891\n1234567892";
var rText = text.Replace("1234567890", "asd");

Console.WriteLine(rText);
Console.ReadKey();

输出是:

asd
1234567891
1234567892

所以,很明显你的问题不在于 String.Replace 方法。 您可以使用简单的代码来“读取整个文件”:

string[] text = File.ReadAllLines(filename);
StringBuilder str = new StringBuilder();
foreach (string s in text) 
    str.AppendNewLine(s);

然后,

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.OpenOrCreate,问题就消失了。

编辑

我没有使用“IsolatedStorageFile”只是因为我没有在 SilverLight 上下文中进行测试,也没有使用 ClickOnce 进行部署,所以它不起作用

【讨论】:

  • 附带说明:Silverlight 并不是唯一可以使用 IsolatedStorage 的地方,它也可用于桌面和 Windows 应用商店应用程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2012-06-24
相关资源
最近更新 更多