【问题标题】:Working with .tmp file for writing data使用 .tmp 文件写入数据
【发布时间】:2015-12-31 19:11:49
【问题描述】:

我想知道在使用 .tmp 文件写入数据时是否有最佳实践。我喜欢制作一个将在文件流中使用的 .tmp,然后当我关闭编写器时,我喜欢重命名文件。有没有办法重命名文件扩展名?

    FileStream stream2 = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
    StreamWriter streamWriter2 = new StreamWriter(stream2);
    streamWriter2.WriteLine(textToAdd);
    streamWriter2.Close();
    string changed = Path.ChangeExtension(fileName, .txt);
    File.Move(path, changed);

【问题讨论】:

  • 你不是用Path.ChangeExtension(...)回答你自己的问题吗?为什么要移动它?
  • 这只会改变字符串值,但之后会发生什么?是不是 File.WriteAllText 那么使用 tmp 文件有什么好处。

标签: c# asp.net .net file-io


【解决方案1】:

我会这样做:

// Build a FileInfo object for your temp destination, this gives us
// access to a handful of useful file manipulation methods
var yourFile = new FileInfo(@"C:\temp\testfile.tmp");

// open a StreamWriter to write text to the file
using (StreamWriter sw = yourFile.CreateText())
{
    // Write your text
    sw.WriteLine("Test");
    // There's no need to call Close() when you're using usings
}

// "Rename" the file -- this is the fastest way in C#
yourFile.MoveTo(@"C:\temp\testfile.txt");

【讨论】:

    【解决方案2】:

    您可以使用Path.GetFilenameWithoutExtension 删除扩展名,然后添加您想要的扩展名。

    【讨论】:

    • 那会调用 File.WriteAllText 类吗?
    猜你喜欢
    • 2016-02-07
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    相关资源
    最近更新 更多