4

I'm using the code below to break apart a large text file into smaller files based on the logic you can see here. I'm getting an error on the File.WriteAllText line saying that tempfile doesn't exist. The flow is one header record, followed by multiple report data rows, followed by one end of report line, then it starts over again. Does anyone know why my temp file wouldn't be created here, what am I missing? Thanks.

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);
        }
    }
}
imjustaboy
  • 326
  • 2
  • 12

1 Answers1

6

This code is getting you problem :

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

Use string interpolation with above code :

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

You can check that where the streamwriter has written the data.

Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • Yes @LolCoder 아카 쉬 that was the issue. This would have been a lot easier had my code given me an error on that line. I'm not sure why it didn't or what exactly happened when it got there, but thank you anyways for the extra pair of eyes that have helped me move on. – imjustaboy Sep 13 '16 at 20:15
  • Sometime, it happens...Glad to help you :) – Akash KC Sep 13 '16 at 20:27
  • 1
    @Gavin it didn't give you an error because `{_processDir}tempfile.txt` is a valid file name. – Dour High Arch Sep 13 '16 at 20:27
  • Yes @DourHighArch it makes sense now, it was creating the file with the unexpected name in my debug directory. Thanks for pointing that out. – imjustaboy Sep 13 '16 at 20:45