How can I get a list of all open named pipes in Windows and avoiding possible exceptions?

前端 未结 2 1699
温柔的废话
温柔的废话 2021-01-12 22:20

Getting the list of named pipes is in ideal case pretty simple and can be found here: How can I get a list of all open named pipes in Windows?

But mentioned solutio

2条回答
  •  清酒与你
    2021-01-12 22:41

    Using one of the .NET 4 APIs returning IEnumerable, you can catch those exceptions:

    static IEnumerable EnumeratePipes() {
        bool MoveNextSafe(IEnumerator enumerator) {
    
            // Pipes might have illegal characters in path. Seen one from IAR containing < and >.
            // The FileSystemEnumerable.MoveNext source code indicates that another call to MoveNext will return
            // the next entry.
            // Pose a limit in case the underlying implementation changes somehow. This also means that no more than 10
            // pipes with bad names may occur in sequence.
            const int Retries = 10;
            for (int i = 0; i < Retries; i++) {
                try {
                    return enumerator.MoveNext();
                } catch (ArgumentException) {
                }
            }
            Log.Warn("Pipe enumeration: Retry limit due to bad names reached.");
            return false;
        }
    
        using (var enumerator = Directory.EnumerateFiles(@"\\.\pipe\").GetEnumerator()) {
            while (MoveNextSafe(enumerator)) {
                yield return enumerator.Current;
            }
        }
    }
    

    The badly named pipes are not enumerated in the end, of course. So, you cannot use this solution if you really want to list all of the pipes.

提交回复
热议问题