Hi,

I fail removing some carriage return, (\n\r i guess) from a god file which brings that the software where i'm exporting to is crying..

if i manually remove the CR from notepad, no problem

i'm googling around for nearly 3 hours now on every possible way i can imagine express this but no luck

my idea is to seek to the end of the file and then to make some substring..but no way

so here's my file :

FileStream fs = new FileStream(@"C:\Users\me\Desktop\output2.csv", FileMode.Append, FileAccess.Write);

StreamWriter sw = new StreamWriter(fs);

but now i don't see any kind of subst or trim methods ?!?!?!?!?

or if i try to read it with :

        StreamReader sr = new StreamReader(@"C:\Users\me\Desktop\output2.csv"))
            {
                char[] c = null;

                while (sr.Peek() >= 0)
                {
                    c = new char[2048];
                    sr.Read(c, 0, c.Length);
                }
            }

by adding a breakpoint on the sr.Read(), I can see that the 2 last char's filed are '\n' and '\r'..

but, for godsake how can i delete them ?

please someone..for our planet..before i throw my laptop out of this window

Dani AI

Generated

Two quick gotchas explain why your earlier attempts failed:

  • ReadAllLines strips line terminators, and WriteAllLines writes a newline after every element it writes, including the last one. So you will always end up with a trailing newline using that pair (File.WriteAllLines).
  • Replace(@"\r", "") searches for a backslash followed by r, not a carriage return. Use "\r" and "\n" for actual control characters.

If you need to clean an existing file without loading it all into memory, truncate the trailing newline(s) in place. This is fast and safe for ASCII/UTF-8 CSVs:

using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
    if (fs.Length == 0) return;
    int trim = 0;

    fs.Position = fs.Length - 1;
    int b = fs.ReadByte();
    if (b == 0x0A) { // LF
        trim = 1;
        if (fs.Length >= 2)
        {
            fs.Position = fs.Length - 2;
            if (fs.ReadByte() == 0x0D) trim = 2; // CRLF
        }
    }
    else if (b == 0x0D) trim = 1; // lone CR

    if (trim > 0) fs.SetLength(fs.Length - trim); // in-place truncate
}

Prevention tip: when writing, avoid adding a newline after the last record.

for (int i = 0; i < lines.Count; i++)
    if (i < lines.Count - 1) writer.WriteLine(lines[i]); else writer.Write(lines[i]);

You can also control the newline sequence via TextWriter.NewLine (TextWriter.NewLine) and learn more about truncation with FileStream.SetLength.

Recommended Answers

All 5 Replies

I tried also this


string[] str = System.IO.File.ReadAllLines(saveFileDialog1.FileName);

string temp = str[str.Length-1].Replace(@"\r", "").Replace(@"\n", "");

str[str.Length - 1] = temp;

System.IO.File.WriteAllLines(saveFileDialog1.FileName, str);

does not work, CR still there

Here's how I'd do it

string myFileData;

// File in
myFileData = File.ReadAllText(@"D:\test.csv");
// Remove last CR/LF
// 1) Check that the file has CR/LF at the end
if (myFileData.EndsWith(Environment.NewLine))
{
  // Yes. 2) Remove CR/LF from the end and write back to file (new file)
  // File.WriteAllText(@"D:\test_backup.csv", myFileData.TrimEnd(null)); // Removes ALL white spaces from the end!
  File.WriteAllText(@"D:\test_backup.csv", myFileData.TrimEnd(Environment.NewLine.ToCharArray())); // Removes ALL CR/LF from the end!
}

Here's two solutions. The first one (line 10.) commented out but you can use it if you want to all trailing white spaces trimmed. The code as is removes now CR/LF (or just LF or CR depending on your environment). If there's multiple CR/LF pairs, the code removes all of them from the end, not just the last one.

HTH

commented: perferct ! helped me out :-) thanks +2
commented: Thanks, 'Teme64' - this was exactly what I needed too - kudos for the awesome code - thanks again! +0

Hi,

man...i owe you one (my computer also)

THANKS so much that work's :-)

try these methods....

Regex.Replace(str, @"\t\n\r", "");

Or

str = str.Replace(System.Environment.NewLine, ",");

Or

str = str.Replace(vbLf, [String].Empty)
str = str.Replace(vbCr, [String].Empty)
str = str.Replace(vbTab, [String].Empty)

Full Source......Remove "\r\n" from a string

Lee

THANKS ...................................THANKS ..........................THANKS
very goooooooooooooooooooooooooooooooooooooooooooooooooooooood

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.