I have searched numerous web pages but I can't seem to find anywhere which shows how to stop a blank line appearing at the end of a file when using StreamWriter.
The code I've written below is the only way I can get this to work for me.. and although this works perfectly fine for the utility I am creating, I would like to know if there is a better/more efficient way to do this?
int count = 0;
int lineCount = newFile.Count;
using (System.IO.StreamWriter extract = new System.IO.StreamWriter(outputFile, true))
{
foreach (var line in newFile)
{
count++;
if (count != lineCount)
{
extract.Write(line + Environment.NewLine);
}
else
{
extract.Write(line);
}
}
}
Any thoughts people?
Since you are accessing the Count
property, it means that your newFile
source implements the IList
interface. This means that you can access it by its index.
Use for
loop instead of foreach
:
for (int i = 0; i < newFile.Count - 1; i++)
{
extract.WriteLine(newFile[i]);
}
extract.Write(newFile[newFile.Count - 1]);
Check this...
var values = Enumerable.Range(1,10);
var output = string.Format(string.Join(",{0}", values), Environment.NewLine);
File.WriteAllText(path, output);
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.