P
P
prog3232014-04-17 22:27:35
RAM
prog323, 2014-04-17 22:27:35

How to free memory in MemoryStream in c#?

while the application is running, 5 or more files are read into memory
while reading files, from 1gb to 5gb of memory is used,
although only 1gb should be used, since each source file that reads the MemoryStream over 1gb
flush / close seems to be doing
please tell me what is the error
how to free it correctly memory before reading new file into memory?

static void Main(string[] args)
        {
            string filePath;                   
            string[] files = { "C:\\001.txt", "C:\\002.txt", "C:\\003.txt" , "C:\\004.txt", "C:\\005.txt", "C:\\006.txt", "C:\\007.txt", "C:\\008.txt" };
                        
            //
            for (int i = 0; i < files.Length; i++)
            {
                    
                FileStream fileStream = File.OpenRead( files[i] );
                using ( fileStream  )
                {

                    MemoryStream memStream = new MemoryStream();
                    memStream.SetLength(fileStream.Length);

                    int l = (int)fileStream.Length;
                    fileStream.Read(memStream.GetBuffer(), 0, l); 

                    using (StreamReader sr = new StreamReader(memStream, Encoding.Default) )
                    {
                        
                    }

                  
                    memStream.Flush(); 
        memStream.Close();
                    
                }
                
                    fileStream.Close();  

            }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
prog323, 2014-04-17
@prog323

already done like this (but 2 gigabytes are sometimes eaten, all files are exactly 1gb)
it is not clear what is being eaten

sr.Close();   sr = null;   if (sr != null) { sr.Dispose(); }; GC.Collect();
memStream.Flush();  memStream.Close();  memStream = null;   if (memStream != null) { memStream.Dispose(); };  GC.Collect();
fileStream.Close(); fileStream = null; if (fileStream != null) { fileStream.Dispose(); };         GC.Collect();

P
plasticmirror, 2014-04-18
@plasticmirror

FileInfo -> file size
new byte[file size]
read directly there
will eat exactly as much as you need
if you need a memorystream - create it on top of the buffer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question