开发者

Deleting a temp file that is open c#

i have written some pdf files to a temp directory and these get displayed as a thumbnail that the user can view. when i close my form i clean up all of the files in the temp directory.

If however the user has one of the thumbnails open and then closes my application - it deletes the files and then throws an exception because the pdf is open in another process and cant be cleaned up.

I guess this is a shocking programming decision by me, but i am still a nov开发者_开发问答ice! How should i account for this in my code?

Thanks


You can detect if the file is in use by using code similar to below, then use that to warn the user that a file can't be deleted. Unfortunately you can't delete a file that is in use.

    public static bool IsFileInUse(string pathToFile)
    {
        if (!System.IO.File.Exists(pathToFile))
        {
            // File doesn't exist, so we know it's not in use.
            return false;
        }

        bool inUse = false;
        System.IO.FileStream fs;
        try
        {
            fs = System.IO.File.Open(pathToFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.None);
            fs.Close();
        }
        catch (System.IO.IOException ex)
        {
            string exMess = ex.Message;
            inUse = true;
        }
        return inUse;
    }


You should catch that exception (in catch block you can inform user to close that file or it will not be deleted), and if the temp directory is yours you can try to delete it when application starts (or when it ends again), if its windows temp directory, then it does not matter that much


Tools like File Unlocker can release a file. However I think this could make programs depending on the file crash...

Maybe you can look up how they unlock files or manage to execute the unlocker via Process.Start to unlock your file and delete it.

However if it's you blocking the file you should try and fix this in your programm. Maybe you should dispose all loaded files (filestreams etc) before trying to clean it up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜