使用.tmp文件写入数据

时间:2015-12-31 19:11:49

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

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

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

您可以使用Path.GetFilenameWithoutExtension删除扩展程序,然后只需添加所需的扩展程序即可。