Visual C# Developer Center > Visual C# Forums > Visual C# General > please help me understand the code C# (very urgent)
Ask a questionAsk a question
 

Answerplease help me understand the code C# (very urgent)

  • Thursday, October 29, 2009 4:47 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    I want to know is below function open and close the file again and again or just open once.

    b/c i am writing to the files at very fast speed 3 message at per 5 milli second . so i don't want to open and close the file again and again reather i want to open the file one time it exit if not exits create it and open it and keep it open and every time messge come i just write to the file and flush the stream


    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();

    }


    It's Me

Answers

  • Tuesday, November 03, 2009 8:59 AMBin-ze ZhaoMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi,

    I think you have a serious problem in your code in first post:
    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();
    }

    If you call this method many times, the fileStream will be create many times and you never close it, this will cause serious memory leak.

    To achieve what you asked, you need to keep these lines of code outside your method and let FileStream s as a global variable :

    filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);

    Make your method like:
    void writing(string msd)
    {
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();
    }

    After your writing option finished, call s.Close() method to Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

    Thanks
    Binze




    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
  • Wednesday, November 04, 2009 12:01 PMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi,

    If you open and close a file (may be C:\a.txt) about 1000 times, then it will take lot of time. YOu can write a small console application for same. If you open it once, do operation and then close it at the end will increase performance.

    If you are not closing file, then you will end up not releasing resources used by stream.

    Smart way to fix this issue is to open file once and close it at the end.

    Thanks
    PKR

All Replies

  • Thursday, October 29, 2009 4:48 AMRon.Whittle Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Yes, it opens and closes it over and over again.


    Ron Whittle - If the post is helpful or answers your question, please mark it as such. Not As Brightly Lit
  • Thursday, October 29, 2009 5:36 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    what if i change it to

     

    FileStream s = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);


    It's Me
  • Thursday, October 29, 2009 5:38 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    what if i change it to append and file access is write

    FileStream s = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);


    if this alos open and close how can i do it with out closing

    It's Me
  • Thursday, October 29, 2009 5:59 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,
        I would say write a new class may be Logger (singleton can help too). This class can have  instance of FileStream as member variable. have methods like write to write data. Close the file at the end.

    Thanks
    PKR

    Note: You can think of extending FileStream to customize if you want.
  • Tuesday, November 03, 2009 8:59 AMBin-ze ZhaoMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi,

    I think you have a serious problem in your code in first post:
    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();
    }

    If you call this method many times, the fileStream will be create many times and you never close it, this will cause serious memory leak.

    To achieve what you asked, you need to keep these lines of code outside your method and let FileStream s as a global variable :

    filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);

    Make your method like:
    void writing(string msd)
    {
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();
    }

    After your writing option finished, call s.Close() method to Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

    Thanks
    Binze




    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
  • Wednesday, November 04, 2009 5:56 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    my filestream is a local variable i belive after the completation of that method . i will be avaiable of GC .. and i will create new Filestream obj again

    M i RIGHT?






    It's Me
  • Wednesday, November 04, 2009 6:06 AMRon.Whittle Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Yes.
    Ron Whittle - If the post is helpful or answers your question, please mark it as such. Not As Brightly Lit
  • Wednesday, November 04, 2009 6:28 AMNagarjunaDilip Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,


    Use
     System.IO.File.AppendText(string path);

    OR

     System.IO.File.AppendAllText(string path,.....);
    Nagarjuna Dilip
  • Wednesday, November 04, 2009 6:33 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    thanks for reply see the code below let say i run the writing method "100 million" time

    with different path and msd ,,,,, will i get a issue related to memory leak ,,,

    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();

    }
    It's Me
  • Wednesday, November 04, 2009 6:37 AMNagarjunaDilip Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,

    No you can go a head with it. Jst check this once and let me know.

    Nagarjuna Dilip
  • Wednesday, November 04, 2009 7:20 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Why memory leak issue my filestream is a local variable so i belive i will not  get memory leak lssue

    M I RIGHT


    It's Me
  • Wednesday, November 04, 2009 7:37 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Hi,
     I still don't understand why you don't close the file. Every time the method is going to create a new instance of filestream. Is is bad if you don't close the file. Try as below (But trust me you will end up in performance issue if you are open and close everytime)

    		void writing(string msg, string path)
    		{
    			string filepath = "d:/" + path + ".txt";
    			using (FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.Write))
    			{
    				fs.Write(Encoding.Unicode.GetBytes(msg), 0, Encoding.Unicode.GetByteCount(msg));
    				fs.Write(Encoding.Unicode.GetBytes(Environment.NewLine), 0, Encoding.Unicode.GetByteCount(Environment.NewLine));
    			}
    		}
    
    
    Hope this helps. There are many threads which discusses the same issue. Isn't?

    Thanks
    PKR
  • Wednesday, November 04, 2009 8:37 AMNagarjunaDilip Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Proposed AnswerHas Code
    Hi,  
    
    //u can call this method N number of times. Jst check out.
    
    void writing(string msg, string path)
    {
       string filepath = "d:/" + path + ".txt";            
        if(!File.Exist(filepath))
        {
           File.Create(filepath);
         }
    
         Syste.IO.File.AppendAllText(filepath, msg, Encodingobject);  
    }
    


    Nagarjuna Dilip
    • Proposed As Answer byNagarjunaDilip Wednesday, November 04, 2009 10:52 AM
    •  
  • Wednesday, November 04, 2009 10:48 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Above code will work but will have performance issues. same is with my code too.
    Thanks
    PKR
  • Wednesday, November 04, 2009 11:10 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    what do you mean by performance issue (it will eat too much memory or process )
    What?
    It's Me
  • Wednesday, November 04, 2009 12:01 PMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi,

    If you open and close a file (may be C:\a.txt) about 1000 times, then it will take lot of time. YOu can write a small console application for same. If you open it once, do operation and then close it at the end will increase performance.

    If you are not closing file, then you will end up not releasing resources used by stream.

    Smart way to fix this issue is to open file once and close it at the end.

    Thanks
    PKR