使用.tmp文件写入数据

本文关键字:数据 文件 tmp 使用 | 更新日期: 2023-09-27 18:28:33

我想知道在使用.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);

使用.tmp文件写入数据

以下是我的操作方法:

// 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");

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