I created a class with the responsibility to generate a text file where each line represents the information of an object of 'MyDataClass' class. Below is a simplification of my code:
public class Generator
{
private readonly Stream _stream;
private readonly StreamWriter _streamWriter;
private readonly List<MyDataClass> _items;
public Generator(Stream stream)
{
_stream = stream;
_streamWriter = new StreamWriter(_stream, Encoding.GetEncoding("ISO-8859-1"));
}
public void Generate()
{
foreach (var item in _items)
{
var line = AnotherClass.GetLineFrom(item);
_streamWriter.WriteLine(line);
}
_streamWriter.Flush();
_stream.Position = 0;
}
}
And I call this class like this:
using (var file = new FileStream("name", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
new Generator(file).Generate();
}
When I run the application on visual studio (I test with run (Ctrl+F5), debug (F5), with debug and release mode) all goes according to the plan. But I publish the application in a IIS server and now StreamWriter class put an extra \r before the end of the line.
Check it out the hexadecimal reading of both generated files:
Running in Visual Studio: http://www.jonataspiazzi.xpg.com.br/hex_vs.bmp
Running in IIS: http://www.jonataspiazzi.xpg.com.br/hex_iis.bmp
Some things I already checked:
Write the
line
variable (invar line = AnotherClass.GetLineFrom(item);
) in a log to see if an extra '\r' is uncluded by the classAnotherClass
.
Didn't result in nothing, the last char in line
is a regular char like expected (in example above is a space).
Write another code to see if the problem is general for all IIS StreamWriter instances.
I tried this:
var ms = new MemoryStream();
var sw = new StreamWriter(ms, Encoding.GetEncoding("ISO-8859-1"));
sw.WriteLine("Test");
sw.WriteLine("Of");
sw.WriteLine("Lines");
sw.Flush();
ms.Position = 0;
In this case the code works well for both visual studio and IIS.
I'm in this for 3 days, I already try everything my brain can think. Did anyone have any clue for what I can try?
UPDATE
Get weirder! I try to replace the line _streamWriter.WriteLine(line);
with:
_streamWriter.Write(linhaTexto + Environment.NewLine);
And even worse:
_streamWriter.Write(linhaTexto + "\r\n");
Both keep generating the extra \r
character.
I try replace with this:
_streamWriter.Write(linhaTexto + "#\r\n#");
And get:
My guess is that the extra \r is added during FTP (maybe try a binary transfer)
Like here
I've tested the code and the extra /r is not due to the code in the current question