【问题标题】:Remove file type from string [duplicate]从字符串中删除文件类型[重复]
【发布时间】:2013-09-03 21:54:44
【问题描述】:

我正在从服务器调用字符串列表。

目前我正在获取全名和文件扩展名,例如:

Image1.jpg

image2.png

test_folder.folder

我有一些代码依赖于知道扩展名是什么,但是我还需要访问我选择的项目的名称,而不需要扩展名。

到目前为止,我的两次尝试如下:

_clickedFolder = listBox1.SelectedItem.ToString() - "folder";
_clickedFolder.Trim(new Char[] { '.folder' });

但这些都不起作用。

什么是去掉文件扩展名而只显示文件名的正确方法?

【问题讨论】:

  • @Sean 看来我们正在一步一步地做你的功课?
  • @MauricioGracia 我同意你的看法,肖恩在 5 分钟内问了两个问题。

标签: c# string


【解决方案1】:

使用Path 类:

string fnWithoutExtension = Path.GetFileNameWithoutExtension(path);

或

string extension = Path.GetExtension(path);

【讨论】:

    【解决方案2】:

    你可以试试这个:

    string name = "set this to file name";
    name = name.Substring(0,name.LastIndexOf('.'));
    

    【讨论】:

      【解决方案3】:

      试试这个;

          private void listBox1_SelectionIndexChanged(object sender,EventArgs e)
          {
          string item = listBox1.SelectedItem.ToString();
          int index = item.LastIndexOf('.');
          if (index >= 0)//It's a valid file
          {
              string filename = item.Substring(0, index );
              MessageBox.Show(filename);
          }
          else if (index == -1)//Not a valid file
          {
              MessageBox.Show("The selected file is invalid.");
          }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        • 1970-01-01
        • 1970-01-01
        • 2013-11-22
        • 2020-03-30
        相关资源
        最近更新 更多