home screen

Search



Number Of Result : 0

Result :


Friday, April 10, 2009

Howto: Create Temporary Files

- As i read a book, i ecnounter this. You can create a temporary file that automaticaly deleted when your program is terminated or the stream was closed. FYI, the Path object of System.IO namespace has its GetTempFileName method that returns a temporary filename:

public class TemporaryFileStream : FileStream {

private TemporaryFileStream() : this(Path.GetTempFileName()) {
}

private TemporaryFileStream(string fileName) : base (fileName, FileMode.Open){
m_fileName = fileName;
}

private readonly string m_fileName = string.Empty;
public string FileName {
get { return m_fileName; }
}

protected override void Dispose(bool disposing) {
base.Dispose(disposing);
//you use try catch here
//if (FileName.Length > 1) {
if (FileName.Length > 1) {
File.Delete(FileName);
m_fileName = string.Empty;
}
}
}


- you may use the tempfile this way


class Program {
static void Main(string[] args) {
TemporaryFileStream tfs = new TemporaryFileStream();
StreamWriter sw = new StreamWriter(tfs);
sw.Write("Kamusta mundo!");
sw.Flush();

//Retrieve what was written
StreamReader sr = new StreamReader(tfs);
string value = sr.ReadToEnd();

//close the file
tfs.Close();
}
}


Track URL : http://msforums.ph/blogs/dehranph/archive/2005/12/01/90470.aspx

No comments: