【问题标题】:Can I access file name and file type by using File.Exists我可以使用 File.Exists 访问文件名和文件类型吗
【发布时间】:2015-03-21 18:05:48
【问题描述】:

filepath 变量来自 UDP 套接字。在我的代码如下之后:

string filename=null;
string filetype=null;
if (File.Exists(filepath)){
     filename=?????;
     filetype=????;
}

我可以访问文件名和文件类型吗?

【问题讨论】:

  • 编程语言应该放在tags中,而不是titles中。
  • @crashmstr 这是我在 stackoverflow 中的第二篇文章。我正在学习,谢谢你:)
  • 通过“文件类型”你只想要扩展名吗?
  • @JamesThorpe 文件类型或扩展名,如“.rar”、“.jpg”、“.txt”等

标签: c# types filenames file-exists file-access


【解决方案1】:
string filename = null;
string filetype = null;
if (File.Exists(filepath)) {
    filename = Path.GetFileName(path);
    filetype = Path.GetExtension(path);
}

【讨论】:

    【解决方案2】:
    var f = new FileInfo(filepath);
    filename = f.Name;
    filetype = f.Extension;
    

    【讨论】:

      【解决方案3】:

      您可以使用 Path 类获取文件名和文件类型。

      filename = Path.GetFileNameWithoutExtension(filepath)
      filetype = Path.GetExtension(filepath)
      

      【讨论】:

      • 非常感谢。这就是我想要的
      猜你喜欢
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2016-12-28
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多