9

I'm playing around with C# and I encountered a problem. When I try to make a new file, the program breaks and says that the file is being used by another process. It's probably something stupid that I overlooked, but I cant figure it out!

Here is my code:

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace myNameSpace
{
    public partial class MainWindow : Form
    {
        public static string folderPath = @"fullpath";
        public MainWindow()
        {
            InitializeComponent();
            StoredTb.Text = folderPath;
            String[] files = Directory.GetFiles(folderPath);
            foreach (string file in files)
                myDropDown.Items.Add(Path.GetFileNameWithoutExtension(file));
        }

        private void myDropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod));
        }

        private void myDropDown_invokedMethod()
        {
            string fullpath = MainWindow.folderPath + myDropDown.SelectedText + ".txt";
            StreamReader sr = new StreamReader(fullpath);
            NameTb.Text = myDropDown.SelectedText;
            DescriptionTb.Text = sr.ReadToEnd();
            sr.Close();
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            File.Create(NameTb.Text + ".txt");
            TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); /* this is where the problem occurs */
            tw.WriteLine("The very first line!");
            tw.Close();
        }
    }
}

Sorry for the long code snippet, but since I'm not sure where the problem originates from I had to include pretty much everything.

7 Answers 7

13

Your problem is that File.Create will open a stream allowing you to do what you like to the file:

http://msdn.microsoft.com/en-us/library/d62kzs03.aspx

A FileStream that provides read/write access to the file specified in path.

Therefore, technically, it is in use already.

Just remove the File.Create altogether. The StreamWriter will handle creating the file if it doesn't exist.

Also, invest in using constructs to properly dispose of your file connections too. Will help avoid this in the future.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It worked. I'll accept in 6 minutes (SO wont let me accept yet)
2

As per MSDN the File.Create Method (String) uses a FileStream which in your case is not being closed. Use something like this:

FileStream fs = new FileStream(NameTb.Text + ".txt");
File.Create(fs);
fs.Close();

or @Muctadir Dinar

var fileStream = File.Create(NameTb.Text + ".txt");
//... do all the writing using fileStream
fileStream.Close();

Comments

1

Use

myDropDown_invokedMethod();

instead of

this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod));

1 Comment

Thanks! It wasn't what caused the exception, but I'll make sure to change it.
1

File.Create returns a FileStream object which holds your file. You should use this object for further task.

var fileStream = File.Create(NameTb.Text + ".txt");
//... do all the writing using fileStream
fileStream.Close();

or you could do just

var fs = File.Create(NameTb.Text + ".txt");
fs.Close();
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); 
tw.WriteLine("The very first line!");
tw.Close();

Comments

1

Your problem seems to be in SaveBtn_Click event, you are using your destination file twice for writing:

File.Create(NameTb.Text + ".txt");
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); 

Remove this line:

File.Create(NameTb.Text + ".txt");

Comments

0

Thats because the File.Create(NameTb.Text + ".txt"); keeps the file open:

try use this instead:

    private void SaveBtn_Click(object sender, EventArgs e)
    {
        using(Stream stream = File.Create(NameTb.Text + ".txt"))
        {
            TextWriter tw = new StreamWriter(stream); /* this is where the problem was */
            tw.WriteLine("The very first line!");
            tw.Close();
        }
    }

This wil force the File.Create to be Disposed when the method has exits. The dispose will close the filehandle (win32 unmanaged handle). Otherwise the file will be closed by the garbage collector, but you never know when.

Comments

0

I see 2 ways: 1)use System.IO.File.WriteAllText http://msdn.microsoft.com/en-us/library/vstudio/8bh11f1k.aspx 2)read about disposing http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.