简体   繁体   中英

Working with .tmp file for writing data

I'm wondering if there is a best practice when it comes to working with .tmp file for writing data. I like to make an .tmp that will be use in the filestream and then when I close the writer, I like to rename the file. Is there a way to rename file extension?

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

Here's how I would do this:

// 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删除扩展名,然后添加所需的扩展名。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM