0

i would like to remove the double quotes from my below text file. i need to input the file using my C# application and read the text file and then remove all the double quotes and give the output. I need to remove all the quotes and make them into perfect four spaced format So how can i do this.

Input file

   Designator   Comment Footprint   Center-X(mm)    Center-Y(mm)

     "C5"   "CAP,1n,50V.0603"   "CAPC1608N" "97.733"    "73.025"
     "C4"   "CAP,1n,50V.0603"   "CAPC1608N" "99.638"    "73.025"
     "C3"   "CAP,1n,50V.0603"   "CAPC1608N" "101.543"   "73.025"
     "C7"   "CAP1233,,1n,50V.0603"  "CAPC1608N" "103.448"   "73.025"
     "C8"   "CAP1233,1n,50V.0603"   "CAPC1608N" "105.353"   "73.025"
     "C9"   "CAP455,1n,50V.0603"    "CAPC1608N" "107.258"   "73.025"
     "C10"  "CAP4522,1n,50V.0603"   "CAPC1608N" "109.163"   "73.025"

My codes from my C# application to input the text file:

private void convert_Click(object sender, EventArgs e)
{
   OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = @"C:\files";
        ofd.Filter = "TXT files (*.txt)|*.txt";
        ofd.FilterIndex = 2;
        ofd.RestoreDirectory = true;
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            int[] cols = new int[] { 15, 30, 15, 20, 12 };
            string[] strLines = System.IO.File.ReadAllLines(fileName);

            StringBuilder sb = new StringBuilder();
            string line = string.Empty;
            for (int i = 0; i < strLines.Length; i++)
            {
                line = RemoveWhiteSpace(strLines[i]).Trim(); // here i am getting error in RemoveWhiteSpace, that it is not in the context
                string[] cells = line.Replace("\"", "").Split(new string[] { " " }, StringSplitOptions.None);
                for (int c = 0; c < cells.Length; c++)
                    sb.Append(cells[c].PadRight(cols[c]));
                sb.Append("\r\n");
            }

            //System.IO.File.WriteAllText(fileName, sb.ToString());
            MessageBox.Show(sb.ToString());
        }
}

How can i do this? Please help me out.

I would like to get the format in below style for all the text file i input. So for the above text file i would like to get the format as shown below

     Designator    Comment          Footprint   Center-X(mm)    Center-Y(mm)

       C5      CAP,1n,50V.0603      CAPC1608N     97.733          73.025
       C4      CAP,1n,50V.0603      CAPC1608N     99.638          73.025
       C3      CAP,1n,50V.0603      CAPC1608N     101.543         73.025
       C7      CAP,1n,50V.0603      CAPC1608N     103.448         73.025
       C8      CAP,1n,50V.0603      CAPC1608N     105.353         73.025
       C9      CAP,1n,50V.0603      CAPC1608N     107.258         73.025
       C10     CAP,1n,50V.0603      CAPC1608N     109.163         73.025
Stacy Kebler
  • 180
  • 1
  • 3
  • 22

4 Answers4

3

The two steps are to read the file and replace the quote marks with nothing.

string allText = File.ReadAllText(ofd.FileName); //read file
string noQuotes = allText.Replace("\"", ""); //replace text

Strings are immutable which is why Replace returns a new string object instead of simply changing the existing allText string.

Alternatively, you may want to use ReadAllLines instead which will return an array of strings where each element is one line of the text file. The theory is the same but you would iterate the array and replace the quotes in each element with the empty string.

If you want to use ReadAllLines and WriteAllLines (to save the file out), you could do this

File.WriteAllLines(@"saveFile.txt", File.ReadAllLines(ofd.FileName)
                                   .Select(s => s.Replace("\"", "")).ToList());

That will do the reading, replacing, and saving in one line (not that fewer number of lines is always better).

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • `Error4 'System.Windows.Forms.OpenFileDialog' does not contain a definition for 'Filename' and no extension method 'Filename' accepting a first argument of type 'System.Windows.Forms.OpenFileDialog' could be found (are you missing a using directive or an assembly reference?)` – Stacy Kebler Oct 29 '14 at 20:49
  • 1
    Sorry, it should be `FileName` with a capital `N` (I've updated it in the answer) – keyboardP Oct 29 '14 at 20:49
  • its taking the file and how can i save the converted file – Stacy Kebler Oct 29 '14 at 20:50
  • 1
    You can use [File.WriteAllText](http://msdn.microsoft.com/en-us/library/system.io.file.writealltext%28v=vs.110%29.aspx) or [File.WriteAllLines](http://msdn.microsoft.com/en-us/library/system.io.file.writealllines%28v=vs.110%29.aspx). The latter if you used `ReadAllLines`. – keyboardP Oct 29 '14 at 20:52
  • yes i got it but what above the format.. Please look my question once more.. i have added one thing.. about the format – Stacy Kebler Oct 29 '14 at 21:00
  • 1
    Did you try with `WriteAllLines` instead? It should maintain linebreaks. What does your output look like? – keyboardP Oct 29 '14 at 21:01
  • 1
    Could you please clarify what you mean? Is the file that's being outputted, called "saveFile.txt" in the example above, the same as the original file selected? Don't forget, the file being selected is not being overwritten in the code above, a new file is being created (called saveFile.txt but you can change that to whatever you like) – keyboardP Oct 29 '14 at 21:06
  • now its showing error `Error 8 The best overloaded method match for 'System.IO.File.WriteAllLines(string, string[])' has some invalid arguments` – Stacy Kebler Oct 29 '14 at 22:37
  • also .. `Error 9 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string[]'` – Stacy Kebler Oct 29 '14 at 22:46
  • please give the old code what you sai was true i was trying to open the old original file – Stacy Kebler Oct 29 '14 at 22:47
  • 1
    Looks like you're targetting .NET 3.5. Change the `ToList` to `ToArray`. – keyboardP Oct 29 '14 at 22:49
2

I would do it this way:

using System.IO;

File.WriteAllText(@"C:/text2.txt", File.ReadAllText(@"C:/text1.txt").Replace("\"", ""));

Update: Shorter solution

IKnowledge
  • 221
  • 3
  • 12
2

You can do this easily with regular expressions:

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

if (ofd.ShowDialog() == DialogResult.OK)
{
    string withoutQuotes = Regex.Replace(File.ReadAllText(ofd.FileName), "\"", "");
    File.WriteAllText(ofd.FileName, withoutQuotes);
}
Matt Jacobi
  • 864
  • 7
  • 17
1

try this example, This will remove the double quotes and reformat your text.

private void Reformat(string fileName)
{
    //Give the column width according to column index.
    int[] cols = new int[] { 12, 35, 25, 15, 15 };
    string[] strLines = System.IO.File.ReadAllLines(fileName);

    StringBuilder sb = new StringBuilder();
    string line = string.Empty;
    string LastComment = string.Empty;
    string CarouselName = "Carousel";
    int iCarousel = 0;

    for (int i = 0; i < strLines.Length; i++)
    {
        line = RemoveWhiteSpace(strLines[i]).Trim();
        string[] cells = line.Replace("\"", "").Split('\t');                    
        for (int c = 0; c < cells.Length; c++)
            sb.Append(cells[c].Replace(" ", "_").PadRight(cols[c]));

        if (cells.Length > 1)
        {
            if (cells[1] != LastComment & i > 0)
            {
                iCarousel++;
                if (iCarousel > 45)
                   iCarousel = 1;
                LastComment = cells[1];
            }

            if (i == 0)
                sb.Append("Location".PadRight(15));
            else
                sb.Append(String.Format("{0}:{1}", CarouselName, iCarousel).PadRight(15));
        }
        sb.Append("\r\n");
    }

    //System.IO.File.WriteAllText(fileName, sb.ToString());
    MessageBox.Show(sb.ToString());
}


private string RemoveWhiteSpace(string str)
{
    str = str.Replace("  ", " ");
    if (str.Contains("  "))
        str = RemoveWhiteSpace(str);
    return str;
}
Shell
  • 6,818
  • 11
  • 39
  • 70