Solved

Reading Text file into Collection in C#

Posted on 2010-09-10
13
560 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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
Wow this really works like a champ. How can i compare two text files created like this. Please let me know
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 74

Expert Comment

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

Author Comment

by:dotnetanu
Comment Utility
I have to compare the files and merge them
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Very gracious Idle. Thx  :)
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
Problem solved
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

763 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

12 Experts available now in Live!

Get 1:1 Help Now