Streamwriter file not created

I use the following code to split a large text file into smaller files based on the logic you can see here. I get an error in the line File.WriteAllText stating that tempfile does not exist. A stream is one header record, followed by several lines of report data, followed by one end of the report line, then it starts again. Does anyone know why my temporary file will not be created here, what am I missing? Thank.

private static void SplitFile()
{
    StreamReader sr = new StreamReader($"{_processDir}{_processFile}");
    StreamWriter sw = null;
    string fileName = string.Empty;
    while (!sr.EndOfStream)
    {
        string line = sr.ReadLine();
        if (line.Split('\t')[0] == "FILEIDENTIFIER")
        {
            //line is a header record
            sw = new StreamWriter("{_processDir}tempfile.txt", false);
            sw.WriteLine(line);
        }
        else if (line.Contains("END OF\tREPORT"))
        {
            //line is end of report
            sw.Close();
            File.WriteAllText($"{_processDir}{fileName}.txt", File.ReadAllText($"{_processDir}tempfile.txt"));
        }
        else
        {
            //line is a report datarow
            fileName = line.Split('\t')[0];
            sw.WriteLine(line);
        }
    }
}
+4
source share
1 answer

This code is causing you problems:

 sw = new StreamWriter("{_processDir}tempfile.txt", false);

Use line interpolation with the code above:

 sw = new StreamWriter($"{_processDir}tempfile.txt", false);

, .

+6

Source: https://habr.com/ru/post/1654500/


All Articles