1

I have this particular problem where file.WriteAllText adds an extra white space at the end of the file.

Im using an Ubuntu OS and have monodevelop installed for my C# coding. Im trying to concatenate two files together i.e file1.txt and file2.txt together. But when I do i see an white space at the end of the file. My code is as below

using System.IO;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string file1 = File.ReadAllText(@"/home/usr/test/file1.txt");
            string file2 = File.ReadAllText(@"/home/usr/test/file2.txt");

            File.WriteAllText(@"/home/usr/test/result.txt", file1.Trim()+file2.Trim());
        }
    }
}

Ideally usage of Trim() function should remove extra spaces at start/end of the string. But when I open my file in edit mode, I see an extra space at the end of the file result.txt. How can I get rid of it or why is it performing this way?

SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179
K C
  • 219
  • 1
  • 4
  • 19
  • The trim can remove white space at the front/End of a string. The file.txt is probably not end with space but with some enters at the end. – Aristos Aug 09 '14 at 14:21
  • Check that you have not run into a line endings issue, i.e LF vs CRLF. Windows use the extra CR character. – user2672165 Aug 09 '14 at 14:21
  • But I'm getting the entries of file1.txt and file2.txt in a string and using the Trim() function on string instead. And also to cross verify I opened file1.txt and file2.txt through gedit and I never found any white spaces there. So we can assure that issue raised somewhere between concatenating and storing back to result.txt – K C Aug 09 '14 at 14:24
  • How to check and get rid of LF and CRLF in my case if it exists – K C Aug 09 '14 at 14:27
  • Try storing `file1.Trim() + "xxxxxxxx" + file2.Trim()` to verify exactly where the whitespace is. – mrmcgreg Aug 09 '14 at 14:28
  • Look at http://stackoverflow.com/questions/873043/removing-carriage-return-and-new-line-from-the-end-of-a-string-in-c-sharp for how to remove carriage return. – user2672165 Aug 09 '14 at 14:37

1 Answers1

-1

Im´getting the same problem with that method, using visual studio. The problem is not on trim.. the problem is with "WriteAllText" that allways add a space at the end of the file.

This seems kind of a bug in .net framework, you can´t do anything to solve it with that method. Instead of WriteAllText, try to use his siblin method To write in binary, you just need to get the binarys from your string and then save it.

http://msdn.microsoft.com/en-us/library/system.io.binarywriter(v=vs.110).aspx

Hope it helps.

Yogurtu
  • 2,656
  • 3
  • 23
  • 23