如何读取已加载到内存中的txt文件的内容

时间:2013-10-04 04:07:44

标签: c#

我有一个应该提取.gz文件并将其加载到内存中的函数,我的问题是,如何将文件内容加载到内存后如何读取文件的内容而不必先将其保存到磁盘? / p>

public static void Decompress2(FileInfo fileToDecompress)
{
    using (FileStream fileStream = fileToDecompress.OpenRead())
    {
        using (var memStream = new MemoryStream())
        {
            string currentFileName = fileToDecompress.FullName;
            string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

            using (FileStream decompressedFileStream = File.Create(newFileName))
            {
                using (GZipStream decompressionStream = new GZipStream(fileStream, CompressionMode.Decompress))
                {
                    byte[] bytes = new byte[4096];
                    int n;
                    while ((n = decompressionStream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        memStream.Write(bytes, 0, n);
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

private int _bufferSize = 16384; 

private void ReadFile(string filename) 
{
StringBuilder stringBuilder = new StringBuilder();     
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);  

using (StreamReader streamReader = new StreamReader(fileStream))     
{        
    char[] fileContents = new char[_bufferSize];         
    int charsRead = streamReader.Read(fileContents, 0, _bufferSize); 

    // Can't do much with 0 bytes        
    if (charsRead == 0)             
        throw new Exception("File is 0 bytes"); 

    while (charsRead > 0)         
    {             
        stringBuilder.Append(fileContents);             
        charsRead = streamReader.Read(fileContents, 0, _bufferSize); 
    }     
} 

}

希望它可以帮到你