c# - Directory.GetFiles() 抛出异常 - 文件夹名称末尾有空格无法识别

标签 c#

我有一个如下所示的文件夹名称:

\\server\pictures\607\27022015\HARD\  //temp dir
\\server\pictures\607\27022015\HARD\550528  //dir name (two spaces behind)
macId //a string representative of a folder name (two spaces behind)

在我的代码中,我通过这样做获得文件夹名称:

if (Directory.Exists(tempDirectoryWithoutMac))
                {
                    var subDirectories = Directory.GetDirectories(tempDirectoryWithoutMac);

                    var directoryToSearch = subDirectories.Where(c => c.Contains(macId.Trim()));

                    if (directoryToSearch.Any())
                    {
                        var newDirectory = directoryToSearch.First();

                        foreach (string filename in Directory.GetFiles(newDirectory))
                        {
                            var retVal = new BitmapImage(new Uri(filename.TrimEnd()));

                            return retVal;
                        }
                    }
                }

如果我检查然后将 newDirectory 复制并粘贴到 Windows 资源管理器中,它会将我带到该文件夹​​;但是,我的代码抛出异常:

The network path was not found.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileSystemEnumerableIterator`1.CommonInit()
   at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
   at System.IO.Directory.GetFiles(String path)
   at URM.ViewModels.CollectionsViewModel.GetImages(String macId, String type)

如果我尝试重命名文件夹,去掉末尾的空格...Windows 说...源文件名和目标文件名相同。

编辑 我正在粘贴此路径(用于显示空格的引号):

“\\服务器\图片\607\27022015\HARD\550528 ”

最佳答案

如果您将 DirectoryInfo 和 FileInfo 对象用作常规字符串的对应对象,您需要处理的空白问题就会少得多,并且能够带来更加面向对象和可靠的解决方案。

您可以按照以下方式执行此操作:

DirectoryInfo tempWithoutMac = new DirectoryInfo(tempDirectoryWithoutMac);

DirectoryInfo MacID = new DirectoryInfo(macId);

DirectoryInfo wantedDir = tempWithoutMac.GetDirectories.Where(c => c.Contains(MacID)).First();

foreach (FileInfo file in wantedDir.GetFiles())

{
       var retVal = new BitmapImage(new Uri(file.fullname));

       return retVal;
}

这只是一个示例,因此您需要对其进行调整以使其适合您,但使用这个概念应该可以帮助您。

干杯,

关于c# - Directory.GetFiles() 抛出异常 - 文件夹名称末尾有空格无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28888525/

相关文章:

c# - WPF BitmapSource 图像源

c# - 依赖注入(inject) (DI) "friendly"库

C#比较两个未知类型的对象(包括引用和值类型)

c# - 从 Fiddler 隐藏我的应用程序产生的 Http(s) 流量

c# - 2 方式 ssl web 服务测试

c# - BeginInvoke() 有时会中断 (System.InvalidOperationException),并在阅读器关闭时尝试调用 Read 无效

c# - C# 中多态覆盖的问题

C# protobuf-net - 默认值覆盖来自 protobuf 数据的值

c# - 我可以使用什么设计模式来完成以下任务

c# - 如何限制 FFMpeg CPU 使用率?