简体   繁体   English

输出索引号并从文件中删除路径

[英]Output an index number and remove the path from file

I wrote this code, it works but there are 2 features I'd like to implement and I can't find out how. 我编写了这段代码,它可以工作,但是我想实现2个功能,我不知道如何实现。

First: How to add an index number before each song so it looks like this: 第一:如何在每首歌曲前添加索引号,如下所示:

  1. Song1 松1
  2. Song2 Song2
  3. Song3 Song3

Second: The output to file includes the path to the file. 第二:文件输出包括文件路径。 How do I remove it? 如何删除它?

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles("E:\\Music", "*", SearchOption.AllDirectories);   

            foreach (string file in files)
            {
                string FileName = Path.GetFileName(file);
                Console.WriteLine(FileName);
                System.IO.File.WriteAllLines("E:\\songs.txt", (files));             
            }          

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();   

        }
    }
}

So, in order to only write the name of the songs and not the whole path, you'll have to use Path.GetFileNameWithoutExtensions . 因此,为了只写歌曲的名称而不是整个路径,您必须使用Path.GetFileNameWithoutExtensions

To write the index before every song, you'll have to switch to a for loop (to work with the index). 要在每首歌曲之前编写索引,您必须切换到for循环(以使用索引)。

Another problem is that you're writing to songs.txt for every song, which is bad. 另一个问题是您正在为每首歌曲写入songs.txt ,这很糟糕。 Here's a code to help you out: 这是一个可以帮助您的代码:

string[] files = Directory.GetFiles(@"C:\Users\Admin\Music\Playlists", "*", SearchOption.AllDirectories);
StringBuilder sb = new StringBuilder();

for (int i = 0; i < files.Length; i++)
{
    sb.AppendLine($"{i + 1}. {Path.GetFileNameWithoutExtension(files[i])}");
    // Each line will be something like: Number. NameOfTheSong
}

// Only save to the file when everything is done
File.WriteAllText("E:\\songs.txt", sb.ToString());
Console.WriteLine("Press any key to exit");
Console.ReadLine();

First of all, I think that you have a problem with this line: System.IO.File.WriteAllLines("E:\\\\songs.txt", (files)); 首先,我认为您对此行有问题: System.IO.File.WriteAllLines("E:\\\\songs.txt", (files));

Because in every loop you are writting the file songs.txt 因为在每个循环中,您都在编写文件songs.txt

About the new features: 关于新功能:

For getting the index, an easy way is to change the foreach loop by a for loop. 为了获得索引,一种简单的方法是通过for循环更改foreach循环。

For getting the file name you can use Path.GetFileName() or Path.GetFileNameWithoutExtension() 要获取文件名,可以使用Path.GetFileName()Path.GetFileNameWithoutExtension()

I hope this can help you. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM