Search code examples
c#filetext.netfile.readalllines

Replacing one specific line in a textfile in c#


I'm having a textfile say something like this:

#TITLE:What's Up
#ARTIST:4 Non Blondes - Whats Up
#MP3:Four Non Blondes - Whats Up.mp3
#COVER:4 Non Blondes - Whats Up [CO].jpg
#BACKGROUND:4 Non Blondes - Whats Up [CO].jpg
#BPM:135
#GAP:32100

it's saved as 4 Non Blondes - Whats Up.txt In the same folder there's a MP3 file which is in this example: 4 Non Blondes - Whats Up.mp3

What i want is to replace the line:

#MP3:Four Non Blondes - Whats Up.mp3

into this line:

#MP3:4 Non Blondes - Whats Up.mp3

Every MP3 line has infront of the line this:

#MP3:[Songname].mp3

I know i can do this manually but i have like 2k files like this, and they all need to link to the correct mp3 file. I'm trying this in C#, but without luck.

This is what i've tried so far:

private static void testMethod(string path)
    {
        var x = System.IO.Directory.GetDirectories(path);
        foreach (var directory in x)
        {
            string[] mp3Files = System.IO.Directory.GetFiles(directory, "*.mp3");
            string[] txtFiles = System.IO.Directory.GetFiles(directory, "*.txt");
            string MP3FileNameWithExtensions = System.IO.Path.GetFileName(mp3Files[0]);
            Console.WriteLine(txtFiles[0]);
            var lines = System.IO.File.ReadAllLines(txtFiles[0]);
            for (int i = 0; i < lines.Length; i++)
            {
                if(lines[i].Contains("#MP3")){
                    Console.WriteLine("Jeeeej working");
                    lines[i] = "#MP3:"+MP3FileNameWithExtensions;
                    System.IO.File.WriteAllLines(txtFiles[0], lines);
                }
            }
        }
    }

Solution

  • As the filename of the .txt file is [Songname].txt, you can use Path.GetFilenameWithoutExtension(files[i]) to get [Songname]. Then replace the #MP3 line with the filename + ".mp3". Now write out the file.

    N.B. You will probably want to make a copy of the directory you are working on just in case something goes wrong.