好吧,我看到的唯一的解決方案是一個相當黑客:
- 寫在一個文件中的數據;
- 使用默認應用程序使用
Process.Start
打開文件;
- 用
File.Delete
刪除文件。
代碼:
// test data that I'll write on the file
var text = Enumerable.Range(0, 1000000).Select(x => x.ToString()).ToArray();
// choose the Desktop folder to verify that
// the file is deleted at the end of the method
var tempDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// choose a random file name that will be unique 99.999999999% of the times
var filePath = Path.Combine(tempDir, Guid.NewGuid().ToString() + ".txt");
// write the file. Here I use WriteAllLines, you can use StreamWriter
File.WriteAllLines(filePath, text);
// start the default app for this path
Process.Start(filePath);
// wait to let the default app to open the file;
// otherwise the app will crash, not finding the file anymore
// just in the middle of the read
// (I put 2 sec, but the time must be verified
// depending on your system and the file size)
Thread.Sleep(2000);
// this will totally delete the file
File.Delete(filePath);
如果你有記事本爲TXT文件的默認應用程序,這就是你會看到:記事本中打開了你的數據,但該文件不存在了。這就是你想要的,不是嗎?您不會在回收站中找到該文件,因此您不會有磁盤空間泄漏。
這個技巧的唯一缺陷是:如果您在應用程序上單擊「保存」,它將不會詢問您要保存文件的路徑。相反,它只是簡單地重新創建文件,就像在刪除之前一樣,並直接保存數據。這是因爲它打開了一個物理文件,它沒有創建一個新文件,所以它會記住filePath並將其用於保存。
如果你沒有找到更多的正確/專業的解決方案,這個可以完成它的工作。
旁白:
我建議你一點點的重構。
第一步,避免重複:
using (var writer = new StreamWriter("file.txt"))
{
var array = grr[0].Keys.ToArray();
writer.WriteLine(array[0] + "," + array[1] + "," + array[2] + "," + array[3]);
for (int r = 0; r < row - 1; r++)
{
var grrr = grr[r].Values.ToArray();
writer.WriteLine(grrr[0] + "," + grrr[1] + "," + grrr[2] + "," + grrr[3]);
}
}
第二步,使用更先進的內置功能:
using (var writer = new StreamWriter("file.txt"))
{
writer.WriteLine(string.Join(",", grr[0].Keys.ToArray()));
for (int r = 0; r < row - 1; r++)
{
writer.WriteLine(string.Join(",", grr[r].Values.ToArray()));
}
}
咦?在你分享的代碼中,新的StreamWriter(「file.txt」)在應用程序的工作目錄中創建一個新文件。你不能兩面都有。要麼你創建一個文件,並且它有一個物理路徑,或者你不創建一個文件。 – adv12
查看https://stackoverflow.com/questions/1232443/writing-to-then-reading-from-a-memorystream,以創建一個Streamwriter到一個內存流,然後再讀取它。 – Joe
如果你只是想要一個內存流(即根本不是文件),請查看[MemoryStream類](https://msdn.microsoft.com/en-us/library/system.io.memorystream(v = vs.110)的.aspx)。 – adv12