Solved

Reading Text file into Collection in C#

Posted on 2010-09-10
13
562 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 

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
 
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

809 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