创建互斥锁会抛出DirectoryNotFoundException

the*_*oop 16 .net mutex

我正在尝试创建一个命名的互斥锁,但是当我调用构造函数时,我得到了一个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)
Run Code Online (Sandbox Code Playgroud)

the*_*oop 19

啊,发现问题所在.我的互斥锁名称包含\在其中,哪些窗口正在解释为路径字符.运行:

mutexName = mutexName.Replace(Path.DirectorySeparatorChar, '_');
Run Code Online (Sandbox Code Playgroud)

解决了这个问题

  • 我建议替换[`Path.GetInvalidPathChars`](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx)中任何字符的任何实例(例如`/ `也无效). (6认同)
  • 这不是一个真正的路径角色,[这里有一个完整的解释](http://stackoverflow.com/a/20714164/1729885).除反斜杠之外的所有字符都是有效的,因为内核对象命名空间. (4认同)