When the file is generated, if the file with the same name in the folder is opened (or used), then a file with the same name is generated, prompting the file to be occupied.
There are two solutions, one is to save the file name to the folder does not exist (random number, such as the Xxoo line, as long as it does not exist), of course, this refers to the name of the file is used, if the same name file is not open, when the file is generated directly overwrite it;
The other is to determine the status of the current file, if the current file is manipulated, then what to do, if not manipulated, then generated.
From the Internet to find a lot of information, today recorded, so as not to use in the future, directly on the code, as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.IO;usingSystem.Runtime.InteropServices;usingSYSTEM.WEB.MVC;namespacehotelinventory.web.models.repository{ Public Static classFileControlRepository1 {[DllImport ("Kernel32.dll")] Public Static externIntPtr _lopen (stringLppathname,intIreadwrite);//Call Windowsdll[DllImport ("Kernel32.dll")] Public Static extern BOOLCloseHandle (IntPtr hobject);//Call Windowsdll Public Const intOf_readwrite =2;//These parameters are not limited, of course, can not be declared, directly assign values to the corresponding function, here is only a raw variable to save it. Public Const intOf_share_deny_none =0x40;//These parameters are not limited, of course, can not be declared, directly assign values to the corresponding function, here is only a raw variable to save it. Public Static ReadOnlyIntPtr Hfile_error =NewINTPTR (-1); Public Static intIsfileopen (stringpath) { stringVfilename =path; if(!file.exists (Vfilename)) { return 0;//file does not exist} IntPtr Vhandle= _lopen (Vfilename, Of_readwrite | Of_share_deny_none);//windows API has a definition extension method above
if (Vhandle = =
{
return 2; // file is occupied
CloseHandle (vhandle);//windows API has a definition extension method above
return 1; // file exists and is not occupied
}
The above code is called directly, path is the full file path, and the namespace should not be forgotten.
C # Determine if the file is being used