Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 593
  • Last Modified:

Reading Text file into Collection in C#

Hi Experts,
                   I want to read the following text in a .txt file into collection in C#. Please help me how to do this.

Begin Folder = "v2_10_0"
    Begin Folder = "v2_10_0_1"
          Script = "alter_udt.sql"
          Script = "dbo.p_test_1.StoredProcedure.sql"
          Script = "dbo.p_test_2 _detail.StoredProcedure.sql"
          Script = "dbo.uf_Split_Data_Into_Table.UserDefinedFunction.sql"
          Script = "update_data_on_udt_columns.sql"
    End
    Begin Folder = "v2_10_0_4"
          Script = "alter_udt.sql"
          Script = "dbo.p_test_4.StoredProcedure.sql"
          Script = "dbo.p_test_4 _detail.StoredProcedure.sql"
          Script = "dbo.uf_Split_Data_Into_Table.UserDefinedFunction.sql"
          Script = "update_data_on_udt_columns.sql"
    End
    Begin Folder = "v2_10_0_5"
        Script = "update_system_info.sql"
    End
    Begin Folder = "v2_10_0_6"
          Script = "dbo.dbo.p_test_6 _detail.StoredProcedure.sql"
         Script = "update_system_info.sql"
    End
END
0
dotnetanu
Asked:
dotnetanu
  • 7
  • 5
1 Solution
 
käµfm³d 👽Commented:
Here is one example. Once this logic completed, you would access each "Script" by doing something like:

    data["v2_10_0"]["v2_10_0_1"][0]
    data["v2_10_0"]["v2_10_0_1"][1]
    data["v2_10_0"]["v2_10_0_1"][2]

etc.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Dictionary<string, StringCollection>> data = new Dictionary<string, Dictionary<string, StringCollection>>();

            using (StreamReader reader = new StreamReader("test.txt"))
            {
                bool foundOuterBegin = false, foundInnerBegin = false;
                string currentOuter = string.Empty, currentInner = string.Empty;

                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine().Trim();
                    string value;

                    if (line.IndexOf('=') >= 0)
                    {
                        value = line.Substring(line.IndexOf('=') + 1).Trim(new char[] { '"', ' ' });
                    }
                    else
                    {
                        value = line;
                    }

                    if (line.ToLower().StartsWith("begin"))
                    {
                        if (foundOuterBegin)
                        {
                            foundInnerBegin = true;
                            currentInner = value;

                            data[currentOuter].Add(currentInner, new StringCollection());
                        }
                        else
                        {
                            foundOuterBegin = true;
                            currentOuter = value;

                            if (!data.Keys.Contains(currentOuter))
                            {
                                data.Add(currentOuter, new Dictionary<string, StringCollection>());
                            }
                        }
                    }
                    else if (line.ToLower().StartsWith("end"))
                    {
                        if (foundInnerBegin)
                        {
                            foundInnerBegin = false;
                        }
                        else if (foundOuterBegin)
                        {
                            foundOuterBegin = false;
                        }
                    }
                    else if (line.ToLower().StartsWith("script"))
                    {
                        if (foundOuterBegin && foundInnerBegin)
                        {
                            data[currentOuter][currentInner].Add(value);
                        }
                    }
                }
            }
        }
    }
}

Open in new window

0
 
dotnetanuAuthor Commented:
Hi Genius,
                  Code is excellent it works great. However how do i write this back to text file. Issue is how to identify which is root begin folder and which one has scripts.

Appreciate your help
0
 
käµfm³d 👽Commented:
Here is a completed project and the resulting output when using your original sample data:


Resulting Data
=========================================================
Begin Folder = "v2_10_0"
      Begin Folder = "v2_10_0_1"
            Script = "alter_udt.sql"
            Script = "dbo.p_test_1.StoredProcedure.sql"
            Script = "dbo.p_test_2 _detail.StoredProcedure.sql"
            Script = "dbo.uf_Split_Data_Into_Table.UserDefinedFunction.sql"
            Script = "update_data_on_udt_columns.sql"
      End
      Begin Folder = "v2_10_0_4"
            Script = "alter_udt.sql"
            Script = "dbo.p_test_4.StoredProcedure.sql"
            Script = "dbo.p_test_4 _detail.StoredProcedure.sql"
            Script = "dbo.uf_Split_Data_Into_Table.UserDefinedFunction.sql"
            Script = "update_data_on_udt_columns.sql"
      End
      Begin Folder = "v2_10_0_5"
            Script = "update_system_info.sql"
      End
      Begin Folder = "v2_10_0_6"
            Script = "dbo.dbo.p_test_6 _detail.StoredProcedure.sql"
            Script = "update_system_info.sql"
      End
      Begin Folder = "v2_10_0_8"
            Script = "TESTING 4"
            Script = "TESTING 5"
      End
End
Begin Folder = "v3_10_0"
      Begin Folder = "v3_10_0_1"
            Script = "TESTING 1"
            Script = "TESTING 2"
      End
End

using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Dictionary<string, StringCollection>> data = ReadFromFile("test.txt");

            data["v2_10_0"].Add("v2_10_0_8", new StringCollection());
            data["v2_10_0"]["v2_10_0_8"].Add("TESTING 4");
            data["v2_10_0"]["v2_10_0_8"].Add("TESTING 5");


            data.Add("v3_10_0", new Dictionary<string, StringCollection>());
            data["v3_10_0"].Add("v3_10_0_1", new StringCollection());
            data["v3_10_0"]["v3_10_0_1"].Add("TESTING 1");
            data["v3_10_0"]["v3_10_0_1"].Add("TESTING 2");

            WriteToFile("test.txt", data);
        }

        static void WriteToFile(string filePath, Dictionary<string, Dictionary<string, StringCollection>> data)
        {
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                foreach (var outerKey in data.Keys)
                {
                    writer.WriteLine(string.Format("Begin Folder = \"{0}\"", outerKey));

                    foreach (var innerKey in data[outerKey].Keys)
                    {
                        writer.WriteLine(string.Format("\tBegin Folder = \"{0}\"", innerKey));

                        foreach (var item in data[outerKey][innerKey])
                        {
                            writer.WriteLine(string.Format("\t\tScript = \"{0}\"", item));
                        }

                        writer.WriteLine("\tEnd");
                    }

                    writer.WriteLine("End");
                }
            }
        }

        static Dictionary<string, Dictionary<string, StringCollection>> ReadFromFile(string filePath)
        {
            Dictionary<string, Dictionary<string, StringCollection>> result = new Dictionary<string, Dictionary<string, StringCollection>>();

            using (StreamReader reader = new StreamReader(filePath))
            {
                bool foundOuterBegin = false, foundInnerBegin = false;
                string currentOuter = string.Empty, currentInner = string.Empty;

                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine().Trim();
                    string value;

                    if (line.IndexOf('=') >= 0)
                    {
                        value = line.Substring(line.IndexOf('=') + 1).Trim(new char[] { '"', ' ' });
                    }
                    else
                    {
                        value = line;
                    }

                    if (line.ToLower().StartsWith("begin"))
                    {
                        if (foundOuterBegin)
                        {
                            foundInnerBegin = true;
                            currentInner = value;

                            result[currentOuter].Add(currentInner, new StringCollection());
                        }
                        else
                        {
                            foundOuterBegin = true;
                            currentOuter = value;

                            if (!result.Keys.Contains(currentOuter))
                            {
                                result.Add(currentOuter, new Dictionary<string, StringCollection>());
                            }
                        }
                    }
                    else if (line.ToLower().StartsWith("end"))
                    {
                        if (foundInnerBegin)
                        {
                            foundInnerBegin = false;
                        }
                        else if (foundOuterBegin)
                        {
                            foundOuterBegin = false;
                        }
                    }
                    else if (line.ToLower().StartsWith("script"))
                    {
                        if (foundOuterBegin && foundInnerBegin)
                        {
                            result[currentOuter][currentInner].Add(value);
                        }
                    }
                }
            }

            return result;
        }
    }
}

Open in new window

0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
dotnetanuAuthor Commented:
I am still using .NET 2.0, Linq does not work for me. Can you please change the var in write file method to equivalent 2.0
0
 
käµfm³d 👽Commented:
Change all occurrences of "var" to "string". I was thinking the loops were going to work with KeyValuePair<> objects, but that is not the case. I usually use "var" as a shortcut when I have to deal with complex generics like KeyValuePair<>.  :)
0
 
dotnetanuAuthor Commented:
Wow this really works like a champ. How can i compare two text files created like this. Please let me know
0
 
käµfm³d 👽Commented:
Compare the files themselves or the collections?
0
 
dotnetanuAuthor Commented:
I have to compare the files and merge them
0
 
käµfm³d 👽Commented:
So my question to you is are you comparing the collections, once the files have been loaded, and then writing out a unique list of Folders and Scripts?
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Good morning kaufmed!

Read his other open PAQ here:
http://www.experts-exchange.com/Programming/Languages/.NET/Q_26463557.html

There are lots of details in there...towards the bottom.  I've just been super busy lately and haven't gotten back to the question.

I'm sure you can whip something up and then get points for both questions!

~IM
0
 
käµfm³d 👽Commented:
Very gracious Idle. Thx  :)
0
 
käµfm³d 👽Commented:
On Idle Mind's cue, I'm going to suggest that this question ("Reading Text file into Collection in C#") has been answered and I will prose an answer to your most recent question in this thread on the thread brought to my attention by Idle Mind, which is of the same subject.
0
 
dotnetanuAuthor Commented:
Problem solved
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 7
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now