Skip to content

File close or overwrite

jeet p

Asked Jul 3, 2009, 2:57 AM EDT2 answers
Share
LinkedInX
Hi all,

I have one windows service made in C#. I want My service to create CSV file every two minutes... but it should overwrite the existing file every two minutes. but whenever I try - it says file is already open - while I am sure that file is processed during those elapsed two minutes.. How do i programmatically close the file or overwrite the same. My file creation is through windows utility CSVDE (so have no control over creation except for the time and name!)


please suggest, thanks,
Jeet

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    C#
    hi all,
    
    came across to wonderful code, i am deleting older files now!
    
    protected void CleanImageFolder()
    {
        string imgFolder = Server.MapPath("~/lab/maskemail/img/");
        string[] imgList = Directory.GetFiles(imgFolder, "*.jpg");
        foreach (string img in imgList)
        {
            FileInfo imgInfo = new FileInfo(img);
            if (imgInfo.LastWriteTime < DateTime.Now.AddMinutes(-3))
            {
                imgInfo.Delete();
            }
        }
    }
    thanks
    jeet
    0
  • 0
    Hi... simple code for you...

    C#
      static void Main(string[] args)
            {
                string date =  DateTime.Now.ToString("yyyyMMddhhmmss");
    
                /* FileMode.OpenOrCreate so the file will be saved! 
                   The date isn't necessary, but i don't want the overwrite the file */
    
                FileStream fs = new FileStream("test" + date + ".CSV", FileMode.OpenOrCreate);
    
                /* also you can using FileMode.Append if the file already exist and you want 
                   to append text into the file without overwrite  */
    
                StreamWriter fso = new StreamWriter(fs);
    
                /* Write something to the file */
                for (int i = 0; i < 100; i++)
                {
                    fso.WriteLine(i);
                }
                /* Save the file */
                fso.Flush();
            }
    0