好吧,我看到的唯一的解决方案是一个相当黑客:
- 写在一个文件中的数据;
- 使用默认应用程序使用
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