只需一步即可存在,读写

时间:2011-10-20 06:13:49

标签: c# file file-handling

我试图找出文件是否存在,如果存在,验证css样式是否已经存在,如果不存在,则将它们写在文件的末尾...

我已经完成了所有这些,但分3步:

文件是否存在?

FileInfo fi= new FileInfo(Path.Combine(rootPath, "DefaultStyles.css");

如果是,我使用TextReader获取内容

using (TextReader tr = new StreamReader(file))
{
    r = tr.ReadToEnd().Contains(".onebyonecard");
    tr.Close();
}

如果找不到样式,我会写入

using (TextWriter tw = new StreamWriter(file))
{
    tw.Write(cssStyle);
    tw.Close();
}

有没有办法在一个简单的打开/关闭中执行此操作,而是需要一遍又一遍地打开文件?

3 个答案:

答案 0 :(得分:3)

那么你可以打开一个单独的流来进行读写 - 但是考虑到你正在阅读整个文件,我个人只需打开它两次。请注意,您当前的代码将覆盖该文件,而不是附加到该文件。

我个人会使用File类中的静态方法:

// Elide this into the "if" condition if you want. I've separated it out here,
// but obviously it makes no difference.
bool present = File.Exists(path) &&
               File.ReadAllText(path).Contains(".onebyonecard);
if (!present)
{
    File.AppendAllText(path, cssStyle);
}

这比具有读/写流并在其上创建TextReaderTextWriter更简单。

几点说明:

  • 通过分离文件访问权限, 存在竞争条件的轻微风险。我们可以打开文件,阅读内容,然后在我们决定下一步做什么时可以更新。同样,当我们执行检查时文件可能存在,但在读取之前被删除。在大多数应用程序中,这种风险非常小,无关紧要 - 只有您可以肯定地说。
  • 如果文件存在但相关用户无法读取/写入,或者其他进程正在使用,则上述代码仍然可以抛出异常。正常的异常处理方式适用 - 决定您认为您可以从这种情况中实际恢复的程度,并采取适当的行动。

答案 1 :(得分:3)

好吧,既然你使用的是ReadToEnd(),你也可以使用:

if (!File.Exists(file) || !File.ReadAllText(file).Contains(".onebyonecard"))
    File.AppendAllText(file, cssStyle);

但这仍然会打开两次。有一些API只允许它打开一次,但那些是二进制API(Stream等) - 这将工作,但对你的场景可能有点过分。

答案 2 :(得分:0)

try
{
TextReader tr = new StreamReader(file);
r = tr.ReadToEnd().Contains(".onebyonecard");
tr.Close();
tr.Dispose ();
}
catch { //File is not exists or is used by another application
}
相关问题