Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Reading Text file into Collection in C#

Posted on 2010-09-10
13
Medium Priority
?
571 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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

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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

604 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