St0ffer
St0ffer

Reputation: 171

File is being used by another process - using FileInfo

I have an SQL Script file where there is a specific line that I want to manipulate at runtime. I came up with the following for that and it works fine. However, I get an exception when trying to run it again, saying the file is being used by another process. Seems like the file is not being closed, but I cannot figure out where and why.

I have a button that does the following among other things:

OpenFileDialog dialog = new OpenFileDialog() { FileName = "Document", DefaultExt = ".csv", Filter = "Comma Seperated File (.csv)|*.csv" };

Nullable<bool> result = dialog.ShowDialog();

string filename = "";

if (result == true)
{
    filename = dialog.FileName;
}

updateSQLScript(filename);

FileInfo file = new FileInfo("\\Tools_TextileMagazine\\CSharp_Template\\Tools_TextileMagazine\\AdditionalFiles\\SQLQuery1.sql");

string script = file.OpenText().ReadToEnd();

SqlConnection conn = new SqlConnection(clsConstants.LOCALDB_CONN_STRING);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);

The method updateSQLScript(filename) only does the following:

string[] arrLine = File.ReadAllLines(clsConstants.PATH_TO_SQL_SCRIPT);

arrLine[9] = String.Format("FROM '{0}'", filename);

//THIS IS WHERE THE EXCEPTION IS THROWN THE SECOND TIME I CLICK THE BUTTON
File.WriteAllLines(clsConstants.PATH_TO_SQL_SCRIPT, arrLine);  

So it seems the other processes happening in the button event is interfering with my updateSQLScript method. I couldn't figure out how to close the file properly before running the method. As far as I could read, I need to use a using statement, but I am not sure how to implement it in this scenario.

Any help would be much appreciated.

Upvotes: 0

Views: 1080

Answers (1)

Cold Machine
Cold Machine

Reputation: 126

I haven't tried running your code, but I think it's this line that's the problem:

string script = file.OpenText().ReadToEnd();

The OpenText() method returns a StreamReader that needs to be closed. Try something like:

string script;
using (StreamReader reader = file.OpenText())
{
    script = reader.ReadToEnd();
}

Upvotes: 2

Related Questions