C# File Handling Problem

vinayphadke 0 Tallied Votes 279 Views Share

Hello Guys,
I was performing text file reading and writting operations and the job looked very simple as usual, yet it has not been solved successfully.
We have got a simple text file final.txt which contains data like this:-
05/18/2012 02:12:66 8HRY hjhruehr737243 YES NO u34gewryge 698 i.e each value separated by ** a space** in between.
We want the output file to be written by replacing space with pipe line character '|' with condition that the the space in time stamp value at the start (05/18/2012 02:12:66) should be retained. so output will look like this
05/18/2012 02:12:66|8HRY|hjhruehr|737243|YES|NO|u34gewryge|698

With my code I'm able to produce the output as given below:
05/18/2012
02:12:66|8HRY|hjhruehr|737243|YES|NO|u34gewryge|698

Now, this is my problem. I want every thing to be written in a single line but whichever method I implement to write file gives me such output.
My code is pasted ; can anyone guide me on this? Thanks in advance.

string tempInput;
    tempInput = File.ReadAllText(@"C:\Documents and Settings\me\Desktop\ssisTemp\final.txt");
    tempInput = tempInput.Trim();
     
    int idxDate = tempInput.IndexOf(" ");
    string strDate = tempInput.Substring(0, idxDate);
    string strCut = tempInput.Substring(idxDate + 1, tempInput.Length - idxDate - 1);
    int nextidx = strCut.IndexOf(" ");
    string strTime = strCut.Substring(0, nextidx);
    string cut2 = tempInput.Substring(idxDate + nextidx + 1, (tempInput.Length - idxDate - nextidx - 1));
    cut2 = cut2.Replace(' ', '|');
    string timeStamp = tempInput.Substring(0, idxDate + nextidx + 1);
    string stroutput = string.Concat(timeStamp, cut2);
    StreamWriter sw = File.CreateText(@"C:\Documents and Settings\me\Desktop\ssisTemp\OUTPUT.txt");
    sw.Write(stroutput);
    sw.Close();
    //MessageBox.Show(@"Please refer to file @ C:\Documents and Settings\me\Desktop\ssisTemp\OUTPUT.txt");

Dani AI

Generated

Most likely cause: the input file contains a line break, tab, or another whitespace character between the date and time rather than a single space. Trimming only removes leading/trailing whitespace, and searching for a literal ' ' will mis-handle other whitespace characters — which explains the line break observed in the output.

A robust, simple approach is to normalize whitespace into tokens and rebuild the output: treat any run of whitespace (space, tab, CR/LF) as a separator, combine the first two tokens back into the timestamp with a single space, and join the remaining tokens with |. This avoids brittle index arithmetic and handles unexpected line endings.

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

var text = File.ReadAllText(@"C:\Documents and Settings\me\Desktop\ssisTemp\final.txt").Trim();
var parts = Regex.Split(text, @"\s+");
if (parts.Length >= 2)
{
    var timestamp = parts[0] + " " + parts[1];
    var rest = parts.Length > 2 ? string.Join("|", parts.Skip(2)) : "";
    var output = timestamp + (rest.Length > 0 ? "|" + rest : "");
    File.WriteAllText(@"C:\Documents and Settings\me\Desktop\ssisTemp\OUTPUT.txt", output);
}

Notes and troubleshooting:

  • ’s fixed-length substring technique is fine when the timestamp format is guaranteed and always the same length; it’s the simplest and fastest in that scenario.
  • ’s replacement loop can work but may unintentionally replace punctuation or multiple character types; tokenizing by whitespace is safer.
  • If fields themselves may contain spaces (e.g., quoted names), a proper parser (CSV-like or a regex matching the exact schema) should be used instead.
  • To confirm the root cause, view the raw file in an editor that shows invisibles (Notepad++, Visual Studio) or inspect character codes to reveal hidden CR/LF, tabs, or non-breaking spaces.
Momerath 1,327 Nearly a Senior Poster Featured Poster

Not sure why you are getting what you say you are getting, but your method is overly complicated. This works:

int index = tempInput.IndexOf(' ');
index = tempInput.IndexOf(' ', index + 1);
String stroutput = tempInput.Substring(0, index) + tempInput.Substring(index).Replace(' ', '|');

And since the date/time is in a specific format, you could even do

String stroutput = tempInput.Substring(0, 19) + tempInput.Substring(19).Replace(' ', '|');
gnath 0 Newbie Poster

Hi Friend, I think this will be an easy one,

 public string RemoveSpecialChars(string str)
        {
            string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "-", "_", "(", ")", ":", "|", "[", "]", " ", "?" };
            //string[] charss = new string[] {"Comma","FullStop","" };
            for (int i = 0; i < chars.Length; i++)
            {
                if (str.Contains(chars[i]))
                {
                    str = str.Replace(chars[i], "|");
                }
            }
            return str;
        }


    after replacing them with that just do
    string.trimend and string.trimstart. . .
    it's all over.. . .
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.