0

When I press enter app twice quickly,the second launching will be crash. I have find out the reason in logs:

"The process cannot access the file '..\filemanifest.xml' because it is being used by another process."

I have researched on many sites and only get answers how prevent app launching twice,not how allow app launching many time. Thanks for all of your help.

How can I allow my app run twice without crash?

Bellash
  • 7,560
  • 6
  • 53
  • 86
Yang Kul
  • 45
  • 1
  • 10
  • Have you tried any of [these](http://stackoverflow.com/questions/414642/wpf-enforce-only-one-instance-of-application) answers? – Mike Eason Jun 03 '15 at 07:10
  • @Mike: I don't want to prevent app launching twice, it means If user press enter many times,many instances of app will be launched. Those solution you gave only allow apps launch 1 time(for this case,I use Mutex is ok). Btw, thanks for your comment – Yang Kul Jun 03 '15 at 07:55

1 Answers1

0

Add to your app metod for check file is in use:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

And just

    for (int i = 0; i < 100; i++)
            {
                if (IsFileLocked(file))
                {
                    //Add what you want
                    Thread.Sleep(1000);
                }
                else
                {
                    //Add what you want
                    return;
                }
            }
galakt
  • 1,374
  • 13
  • 22
  • This error happen when I launch app and file xml is auto created. It has the path like "AppName.exe\filemanifest.xml". So I think i can't apply your code just because I don't know where it's created. – Yang Kul Jun 03 '15 at 07:58
  • @galakt Surely if the application is itself reading this file, then this will always return *"the file is in use"*? Just a hunch. – Mike Eason Jun 03 '15 at 08:00