The process cannot access the file because it is being used by another process

Dineshkumar.S 456 Reputation points
2023-02-09T13:53:39.9233333+00:00

I tried to update me db schema in my code and after changing that if i run my application i ma getting the error as follows
The process cannot access the file because it is being used by another process

but my db is not opened anywhere so how to update the db schema

my code : i have changed my db schema from 107 to 108 in my code given below

can anyone help me to solve this ? thanks in advance

 static void CheckDbCompat()
        {
            EYE.Client.EyeApiAdapter api = new EYE.Client.EyeApiAdapter();
            string mainPath = Path.Combine(api.GetSqliteDataDir(), EYE.Model.DbCM.GetSqliteEyeMainFileName());

            if (File.Exists(mainPath))
            {
                string strSchemaVersion = DbCM.GetVar("dbSchemaVersion", "");
                if (!Int32.TryParse(strSchemaVersion, out int nSchemaVersion))
                {
                    nSchemaVersion = 106;
                }
                if (nSchemaVersion < 108)  //major change so Start Over
                {
                    BaseUtil.WriteToAppConfig("BootstrapState", "");
                }
            }
            
        }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,454 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 59,026 Reputation points
    2023-02-09T15:36:45.76+00:00

    None of the code you posted actually does anything other than check for a file to exist. This code doesn't open any files so it wouldn't trigger the error you're talking about. What you need to do is look at the file that is being locked (I assume mainPath) and ensure that any calls to open the file also close the file. That is what the using statement is for.

    using (var stream = File.OpenWrite(mainPath))
    {
    };  //File is automatically closed when done, even on error
    
    //File is never properly closed
    var stream2 = File.OpenWrite(mainPath);
    stream2.Close(); //Don't do this as it is not exception safe
    
    //Will fail because file is already open, doesn't matter that it is the same process
    var stream3 = File.OpenWrite(mainPath);
    

    If you're using some data library or something that wraps all this then you need to ensure it is cleaning things up as well.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.