SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = " doc files(.doc)|.doc|All files(.)|.";
sfd.FileName = "111";
MyFileName = sfd.FileName;
if (sfd.ShowDialog() == DialogResult.OK)
第一个问题:我保存一个文档,如若有同名文档,他只会提示是否覆盖。怎么写代码能够像Windows系统那样提供多种选择如下图。
第二个问题:如果此同名文档一打开,将无法覆盖会报错,如何判断此文档是否已经打开。是用名称为检索条件判断搜索其进程吗,这个不懂?windows的处理结果如下图,能够做到Windows系统这样就可以。
如果能解决问题会追加悬赏,谢谢!
同名文件覆盖的提示自己做一个窗体来处理就可以了。
要检测文件被那个进程占用,需要使用微软提供的工具Handle.exe,微软提供的https://docs.microsoft.com/zh-cn/sysinternals/downloads/handle,里面也有其他进程处理工具。
我们可以在c#中调用Handle.exe 来检测到底哪个进程占用了文件
string fileName = @"c:\aaa.doc";//要检查被那个进程占用的文件
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();
}
1、同名文件,会提示已覆盖,这个可以自己设计一个窗口实现
2、文件被进程占用问题,可以参考:
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
public const int OF_READWRITE = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
///
/// 文件是否被打开
///
///
///
public static bool IsFileOpen(string path)
{
if (!File.Exists(path))
{
return false;
}
IntPtr vHandle = _lopen(path, OF_READWRITE | OF_SHARE_DENY_NONE);//windows Api上面有定义扩展方法
if (vHandle == HFILE_ERROR)
{
return true;
}
CloseHandle(vHandle);
return false;
}