我需要做的是在内存中创建一个文件,写入该文件,然后像访问任何其他文件一样访问该文件。
我在这里创建并使用实际文件:
if (!File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.csv")))
{
File.Create(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.csv")).Dispose();
using (TextWriter tw = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.csv")))
{
foreach (string[] array in listOfRows)
{
string dataString = array[0] + "," + array[1] + "," + array[2] + "," + array[3];
tw.WriteLine(dataString);
}
tw.Close();
}
}
else if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.csv")))
{
using (TextWriter tw = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.csv")))
{
foreach (string[] array in listOfRows)
{
string dataString = array[0] + "," + array[1] + "," + array[2] + "," + array[3];
tw.WriteLine(dataString);
}
tw.Close();
}
}
//makes virtual table to be copied to database
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.csv")))
{
//etc etc etc
}
正如您所看到的,目前我只是创建一个文件,然后将数据写入其中,然后使用该文件。如果我可以在虚拟内存中完成所有这些操作对我来说会好得多,这可能吗?
答案 0 :(得分:4)
好吧,您可以使用MemoryStream
读/写字节数组。你没有得到" line"用这种方法,但它很接近。
话虽如此,如果您正在写作并立即阅读文件,这听起来就像是在兔子洞的下方。文件用于持久性。
如果您只想在内存中存储一系列字符串,则需要使用StringBuilder
或者只使用List<T>
。
答案 1 :(得分:1)
听起来你想要一个内存映射文件(需要.Net 4或更高版本)来自MSDN:
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
long offset = 0x10000000; // 256 megabytes
long length = 0x20000000; // 512 megabytes
// Create the memory-mapped file.
using (var mmf = MemoryMappedFile.CreateFromFile(@"c:\ExtremelyLargeImage.data", FileMode.Open,"ImgA"))
{
// Create a random access view, from the 256th megabyte (the offset)
// to the 768th megabyte (the offset plus length).
using (var accessor = mmf.CreateViewAccessor(offset, length))
{
int colorSize = Marshal.SizeOf(typeof(MyColor));
MyColor color;
// Make changes to the view.
for (long i = 0; i < length; i += colorSize)
{
accessor.Read(i, out color);
color.Brighten(10);
accessor.Write(i, ref color);
}
}
}
}
}
public struct MyColor
{
public short Red;
public short Green;
public short Blue;
public short Alpha;
// Make the view brighter.
public void Brighten(short value)
{
Red = (short)Math.Min(short.MaxValue, (int)Red + value);
Green = (short)Math.Min(short.MaxValue, (int)Green + value);
Blue = (short)Math.Min(short.MaxValue, (int)Blue + value);
Alpha = (short)Math.Min(short.MaxValue, (int)Alpha + value);
}
}