Solved

Reading Text file into Collection in C#

Posted on 2010-09-10
13
561 Views
Last Modified: 2012-05-10
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
Comment
Question by:dotnetanu
  • 7
  • 5
13 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33648919
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
 

Author Comment

by:dotnetanu
ID: 33649631
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33649844
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
 

Author Comment

by:dotnetanu
ID: 33650743
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
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 33650918
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
 

Author Comment

by:dotnetanu
ID: 33651124
Wow this really works like a champ. How can i compare two text files created like this. Please let me know
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33655894
Compare the files themselves or the collections?
0
 

Author Comment

by:dotnetanu
ID: 33658803
I have to compare the files and merge them
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33662161
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 33662631
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33666219
Very gracious Idle. Thx  :)
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33672355
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
 

Author Closing Comment

by:dotnetanu
ID: 33761564
Problem solved
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now