N
N
Nonpacie2020-09-15 23:13:08
C++ / C#
Nonpacie, 2020-09-15 23:13:08

Why does the stream itself terminate when writing data to a file without throwing an exception?

I have a code that, along the path to the folder, takes all the mp3 files, reads the artist tags and the title, and outputs them to a text file line by line. Everything seems to be working, but literally at the end, ~(1180\1200) breaks the record in the middle of the line and ends the execution without reaching the end of the list of files and without even adding the artist and title to the end.

Skr*ptonite - Chains (feat. 104)(OK)

Skr*ptonit - I'm not <-(??? It shouldn't be like this)

Well, the question is actually, what could go wrong?

THE CODE:

using System;
using System.IO;
using System.Text;
using TagLib;
//using File = TagLib.File;

namespace mp3ToSpotify
{
    internal class Program
    {
        private static void Main()
        {
            //Директория с музыкой
            var dir = new DirectoryInfo(@"F:\Music");

            //Экземляр потока файлов
            FileStream fs = null;

            //Экземпляр класса для ображениям к тегам
            TagLib.File tagFile = null;

            //Создаем поток данных в указаный файл
            fs = new FileStream(@"F:\music10.txt", FileMode.Create);

            var sw = new StreamWriter(fs, Encoding.UTF8);
            
            //За каждую итерацию мы перебираем каждый последующий файл, подставляя путь к каждому последующему файлу в
            //tagFile. После обращаясь уже к самому файлу берём тег исполнителя и названия песни и вписываем в файл построчно.
            foreach (var file in dir.GetFiles("*.mp3"))
                try
                {
                    tagFile = TagLib.File.Create(file.FullName);
                    sw.WriteLine("{0} - {1}", string.Join(", ", tagFile.Tag.Performers), tagFile.Tag.Title);
                }
                catch (CorruptFileException)
                {
                    Console.WriteLine("Error!");
                    throw;
                }
            Console.WriteLine("Finish!");
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2020-09-15
@Nonpacie

And who will close the file, call Flush to flush the cached data to disk?

Q
Qualiant, 2020-09-16
@Qualiant

You can also use using to simplify life, which will call Dispose itself, which will do all the necessary procedures.

using(fs = new FileStream(@"F:\music10.txt", FileMode.Create))
{
    using(var sw = new StreamWriter(fs, Encoding.UTF8))
    {

    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question