c# - 如何获取 Windows 中所有打开的命名管道的列表并避免可能的异常?

标签 c# .net named-pipes

在理想情况下获取命名管道列表非常简单,可以在这里找到: How can I get a list of all open named pipes in Windows?

但是提到了解决方案

var namedPipes = Directory.GetFiles(@"\\.\pipe\");

偶尔会有不可预测的结果。上面的链接中提到了其中一个(Invalid character in path exception)。今天我遇到了自己的异常(exception):

ArgumentException "The second path fragment must not be a drive or UNC name. Parameter name: path2".

问题是 .net 中是否有任何真正有效的解决方案来获取所有打开的命名管道的列表?谢谢

最佳答案

我深入研究了 Directory 类源代码并找到了灵感。这是一个有效的解决方案,它为您提供所有打开的命名管道的列表。我的结果不包含\\.\pipe\前缀,因为它可以在 Directory.GetFiles 的结果中看到。我在 WinXp SP3、Win 7、Win 8.1 上测试了我的解决方案。

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    struct WIN32_FIND_DATA
    {
        public uint dwFileAttributes;
        public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
        public uint nFileSizeHigh;
        public uint nFileSizeLow;
        public uint dwReserved0;
        public uint dwReserved1;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string cFileName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
        public string cAlternateFileName;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);


    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA
       lpFindFileData);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool FindClose(IntPtr hFindFile);

    private static void Main(string[] args)
    {
        var namedPipes = new List<string>();
        WIN32_FIND_DATA lpFindFileData;

        var ptr = FindFirstFile(@"\\.\pipe\*", out lpFindFileData);
        namedPipes.Add(lpFindFileData.cFileName);
        while (FindNextFile(ptr, out lpFindFileData))
        {
            namedPipes.Add(lpFindFileData.cFileName);
        }
        FindClose(ptr);

        namedPipes.Sort();

        foreach (var v in namedPipes)
            Console.WriteLine(v);

        Console.ReadLine();
     }

关于c# - 如何获取 Windows 中所有打开的命名管道的列表并避免可能的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109491/

相关文章:

c# - mvc3-根据模型属性添加CSS类

c# - 如何使用c#在apache drill中显示来自sql server的数据

python - 在 Python 3.7 中使用和重叠命名管道

.net - 在 Jpg vb.net 上编辑 IPTC 元数据

.net - 如何使用对称 key 配置 Microsoft JWT?

C 从命名管道读取不会结束

c - C语言的FIFO读取和删除

c# - 如何通过 COM 互操作将字符串集合从 C# 返回到 C++

c# - 资源争用

c# - 如何在 C# 注释中引用类的索引器成员