没空啰嗦,直接上代码!
class FileOperate
{//for security , not display the account in the app.config
private string RemoteServer = ConfigurationSettings.AppSettings["RemoteServer"];
private string sharefolder = @"\\" + ConfigurationSettings.AppSettings["RemoteServer"];
private string localfolder = ConfigurationSettings.AppSettings["RemoteLocalDisk"];
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x40;
private readonly IntPtr HFILE_ERROR = new IntPtr(-1);
private string CloseFileHandler(string trgFile)
{
string strReturn = "";
try
{
trgFile = trgFile.ToLower();
string local_file_name = trgFile.Replace(sharefolder, localfolder);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe"; //设定程序名
string strLoginName="XXXXX"; //登录名
string strPWD = Encryption.DESDecrypt("XXXXXXX"); //登陆密码
string cmd_args = " /c openfiles /disconnect /op \"" + local_file_name + "\" /ID * /s " + RemoteServer + " /u "+strLoginName+" /p " + strPWD;
p.StartInfo.Arguments = cmd_args; //设定程式执行参数
p.StartInfo.UseShellExecute = false; //关闭Shell的使用
p.StartInfo.RedirectStandardInput = true; //重定向标准输入
p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
p.StartInfo.RedirectStandardError = true; //重定向错误输出
p.StartInfo.CreateNoWindow = true; //设置不显示窗口
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start(); //启动程序
p.WaitForExit();
}
catch(Exception ex)
{
strReturn = ex.Message;
}
return strReturn;
}
public string TryReleaseFileHandler(string strSourchPathFile)
{
string strReturn = "";
IntPtr vHandle = _lopen(strSourchPathFile, OF_READWRITE | OF_SHARE_DENY_NONE);
try
{
if (vHandle == HFILE_ERROR)
{
strReturn = CloseFileHandler(strSourchPathFile);
}
}
catch (Exception ex)
{
strReturn = ex.Message;
}
finally
{
CloseHandle(vHandle);
}
return strReturn;
}
}