修剪文件名以获取变量

Trimming File name to get Variables

我想知道修剪文件名以获得特定变量的最佳方法是什么。例如文件名为:

5000+10-08-2018_Image2.jpg

我想要的是 5000 和 10-08-2018 分开,所以我这样做了:

 string input = file.Name;
 int index = input.IndexOf("_");
 if (index > 0)
    input = input.Substring(0, index);
 string newInterval = input;

我得到“5000+2018-02-05”。我怎样才能进行下一步以将这些值分开。我试过这个:

     string input = file.Name;
     string input2 = file.Name;
     int indexInterval = input.IndexOf("+");
     int indexDate = input2.IndexOf("_");
     if (indexInterval > 0)
        input = input.Substring(0, indexInterval);
     if (indexDate > 0)
        input2 = input2.Substring(0, indexDate);
     string newInterval = input;
     string newDate = input2;

我得到“5000”和“5000+10-08-2018”。

我是 C# 编码的新手 ASP.NET,如有任何帮助,我们将不胜感激。谢谢你。

我会先使用 Path.GetFileNameWithoutExtension,然后 IndexOf + Remove:

string fn = Path.GetFileNameWithoutExtension(file.Name);
int plusIndex = fn.IndexOf('+');
if(plusIndex > -1)
{
   string beforePlus = fn.Remove(plusIndex); 
}

您应该尝试获取从 indexInterval 到 indexDate 的子字符串。

    string input = file.Name;
    string input2 = file.Name;
    int indexInterval = input.IndexOf("+");
    int indexDate = input2.IndexOf("_");
    if (indexInterval > 0)
        input = input.Substring(0, indexInterval);

    if (indexDate > 0)
        input2 = input2.Substring(indexInterval + 1, indexDate - indexInterval - 1);

    string newInterval = input;
    string newDate = input2;

您可以根据指定的分隔符拆分字符串。

string fileName = "5000+10-08-2018_Image2.jpg";
string[] underscoreParts = fileName.Split(new char[] { '_' });
if (underscoreParts.Length > 0)
{
    string[] plusParts = underscoreParts[0].Split(new char[] { '+' });
    Console.WriteLine($"{plusParts[0]}\n{plusParts[1]}");
}

这个returns:

5000
10-08-2018