【问题标题】:How to check if a file exists when it was no file extension? C# [duplicate]没有文件扩展名时如何检查文件是否存在? C# [重复]
【发布时间】:2015-09-05 07:23:49
【问题描述】:

文件测试没有扩展名,我需要帮助才能将此文件移动或重命名为带有扩展名的文件

if(File.Exists(@"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{                                                                 /\
                                               this file has no file extension
}

【问题讨论】:

  • 你忘记了"C:\\Users"之后的`\\`
  • 另外,当使用@"" 时,您不需要对反斜杠进行双重转义。
  • 不要发布重复的问题
  • 使用 System.IO.Path.Combine。还有一种获取桌面目录的推荐方法:Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

标签: c# file io exists


【解决方案1】:

试试这样:

DirectoryInfo d = new DirectoryInfo("directory path");
FileInfo[] f = d.GetFiles("test.*");
if (f.Length > 0)
{
   File.Move(oldPath, newPath);
}
else
{
  //File does not exist
}

同时检查Directory.GetFiles

【讨论】:

  • “像这样尝试”不是答案。您也没有尝试理解OP的问题,您只是回答了标题。
【解决方案2】:

我在文件夹M:\Incoming 中创建了一个名为test 且没有扩展名的文件。

在这两种情况下都可以运行以下代码:

if (File.Exists(@"M:\Incoming\test"))
    Console.WriteLine("Exists");

if (File.Exists(@"M:\\Incoming\\test"))
    Console.WriteLine("Exists");

当使用@ 时,您不需要指定两个斜杠,尽管在本示例中无论如何都没有区别。

输出:

存在

存在

您的问题很可能出在您连接字符串的方式上。

【讨论】:

    【解决方案3】:

    使用目录信息获取目录中的文件列表,然后对于那些没有扩展名的文件,将其删除。

    【讨论】:

      猜你喜欢
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2016-02-04
      • 2011-11-25
      相关资源
      最近更新 更多