1

need your eye on this.

void testSave()
    {
        fileName = curMonth.Text + curYear.Text + ".csv";
        if (!File.Exists(path+fileName))
        {
            File.Create(path + fileName);
        }
        else if (File.Exists(path + fileName))
        {
         try
           {
               lines = curDate.Text + "," + myDesc.Text + "," + myAmount.Text;
                File.AppendAllText(path + fileName, lines + Environment.NewLine);
                TextWriter tw = new StreamWriter(path + fileName, true);
                tw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }             
    }

The error come out as below:

The process cannot access the file 'C:\Users...\File.csv' because it is being used by another process.

Any suggestion or solution i could refer? thanks

NewBieS
  • 147
  • 2
  • 10
  • You can remove all the lines of code, except for `File.AppendAllText`. You don't need to check for file existence and create file manually. `File.AppendAllText` creates file if it does not exist. You also do nothing with your `TextWriter` - it simply opens a file and closes it without writing to it. – Yeldar Kurmangaliyev Aug 16 '16 at 08:55
  • I want to check for the file existence because if that is new file i wanna to add some header before the data go in, if there any ways to do so? – NewBieS Aug 16 '16 at 09:07

1 Answers1

0
  • File.Create(path + fileName); is not closed so you cannot reopen.

  • remove the else keyword if you want.

    void testSave()
    {
        fileName = curMonth.Text + curYear.Text + ".csv";
        if (!File.Exists(path+fileName))
        {
            try
            {
                File.Create(path + fileName).Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    
        try
        {
           lines = curDate.Text + "," + myDesc.Text + "," + myAmount.Text;
            File.AppendAllText(path + fileName, lines + Environment.NewLine);
            TextWriter tw = new StreamWriter(path + fileName, true);
            tw.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    
Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71