修剪文本文件中的每一行,然后将结果保存到数组中

本文关键字:然后 结果 保存 数组 一行 文件 文本 修剪 | 更新日期: 2023-09-27 18:14:58

我需要读取一个本地文本文件,每一行都有一个文件名。每个文件名都需要修剪它的扩展名。当我到达需要将修剪结果保存到另一个数组的部分时,我遇到了一些麻烦。

到目前为止,我有:

string path = @"C:'Users'path'file.txt";
      string[] readText = File.ReadAllLines(path);
      foreach (string s in readText)
      {
          string result = Path.GetFileNameWithoutExtension(s);
          //here I can print the result to the screen 
          //but I don't know how to save to another array for further manipulation    
      }
如果你需要进一步的说明,我会尽我最大的努力让你更清楚。提前感谢。

修剪文本文件中的每一行,然后将结果保存到数组中

你也可以使用Linq:

var path = @"C:'Users'path'file.txt";
var trimmed =
    File.ReadAllLines(path)
        .Select(Path.GetFileNameWithoutExtension)
        .ToArray();

使用for循环代替foreach:

string path = @"C:'Users'path'file.txt";
string[] readText = File.ReadAllLines(path);
for( int i = 0; i < readText.Length; i++ )
    readText[i] = Path.GetFileNameWithoutExtension( readText[i] );

分配一个与原数组大小相同的新数组,然后通过索引插入。

  string path = @"C:'Users'path'file.txt";
  string[] readText = File.ReadAllLines(path);
  string[] outputArray = new string[readText.Length];
  int index = 0;
  foreach (string s in readText)
  {
      outputArray[index++] = Path.GetFileNameWithoutExtension(s);
  }
相关文章: