创建互斥体时抛出DirectoryNotFoundException异常

19
我正在尝试创建一个命名互斥体,但是当我调用构造函数时,我会收到一个DirectoryNotFoundException!为什么互斥体要访问文件系统,我如何知道什么是有效的路径?是否有特定的目录应放置互斥体,以及它如何对应名称?
编辑:我正在使用Mutex(bool, string)重载,并且异常是:
System.IO.DirectoryNotFoundException: Could not find a part of the path '<mutex name>'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Threading.Mutex.<>c__DisplayClass3.<.ctor>b__0(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)

1
你正在使用哪个构造函数,异常的详细信息是什么? - Andrew Barber
哎呀,这个问题才发布了15分钟,已经成为“mutex directorynotfoundexception”谷歌搜索的第二个结果了。爬虫速度真快。 - Wyzard
哇!这个DirectoryNotFoundException完全是误导性的。 - Tigerware
1个回答

23

啊,找到了问题所在。我的互斥锁名称包含了 \ 字符,在 Windows 中被解释为路径字符。执行以下命令:

mutexName = mutexName.Replace(Path.DirectorySeparatorChar, '_');

修复了这个问题


6
我建议将任何包含Path.GetInvalidPathChars中任意一个字符的实例替换掉(例如,/也是无效的)。 - Richard
6
这并不是一个路径字符,这里有完整的解释。除了反斜杠之外,所有字符都是有效的,因为有内核对象命名空间的存在。 - Niels Keurentjes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接