苏飞论坛

标题: C#怎么复制被其他程序占用的文件? [打印本页]

作者: a475313790    时间: 2017-5-24 15:04
标题: C#怎么复制被其他程序占用的文件?
我现在的思路就是 首先通过判断 文件是否被其他程序占用
被占用 通过文件 找到进程,然后杀掉进程,
杀掉进程后 复制文件
/// <summary>
/// 判断文件是否被占用 vFileName为文件的路径+文件名称
/// </summary>

public string IsUnlocker(string vFileName)
        {
            if (!File.Exists(vFileName))
            {
                return "Nofiles";
            }
            IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vHandle == HFILE_ERROR)
            {
                return "true";
            }
            CloseHandle(vHandle);
            return "false";
        }


///<summary>
/// 通过调用外部程序解除文件被占用,fileName为要检查被那个进程占用的文件  
///</summary>
public void KillFiles(string fileName)
{
            Process tool = new Process();
            tool.StartInfo.FileName = "handle.exe";
            tool.StartInfo.Arguments = fileName + " /accepteula";
            tool.StartInfo.UseShellExecute = false;
            tool.StartInfo.RedirectStandardOutput = true;
            tool.Start();
            tool.WaitForExit();
            string outputTool = tool.StandardOutput.ReadToEnd();
            string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
            foreach (Match match in Regex.Matches(outputTool, matchPattern))
            {
                Process.GetProcessById(int.Parse(match.Value)).Kill();
            }

}
///<summary>
///复制文件
///</summary>
public void CopyFolder(string strFromPath, string strToPath)
{
            try
            {...}

            catch
            {...}
}
复制文件的我就简写了

现在有没有更好方式可以 实现我现在想要的功能呢?@站长苏飞



作者: 站长苏飞    时间: 2017-5-25 13:57
你已经接触被占用了,那么直接复制文件就行了吧。




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4