简体   繁体   中英

Streamwriter file is not being created

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);
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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