Solved

Convert an Array to a String or StreamReader??

Posted on 2009-04-02
10
851 Views
Last Modified: 2013-12-17
I know this sounds far fetched but here's what I would like to do.
I would like to pass a text file (i.e. ProofOfConcept -f c:\data.txt) into a Console app called ProofOfConcept as an argument. Next I would like to take that one Argument in the string[] args Array, and pass it into a StreamReader to open that file up, and , eventually store all the data in that pass in file to an Array or ArrayList. (Uncompleted code below)
Is there some way to do this?
Thank you for your time and expertise,
Wally
static void Main(string[] args)
        {
List<Program> nodeList = new List<Program>();
            List<string> workstations;
 
            StreamReader sr = new StreamReader();
            args.
 
            int idx = Array.IndexOf(args, "-f");
            string filename = "";
            if (idx != 1)
            {
                filename = args[idx + 1];
            }
 
            if (args.Length > 0)
            {
                // Load command line arg into List<string> collection
                // assuming comma-seperated values
                workstations = new List<string>(filename.Split(','));
                foreach (string wkstn in workstations)
                {
                    Program node = new Program();
                    node.NodeToPing = wkstn;
                    nodeList.Add(node);
                }
 
            }

Open in new window

0
Comment
Question by:wally_davis
[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
10 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 24053474
Try this:
            List<string> workstations = new List<string>();
 
            int idx = Array.IndexOf(args, "-f");
            string filename = "";
 
            if (idx != -1)
            {
                filename = args[idx + 1];
 
                if (System.IO.File.Exists(filename))
                {
                    System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
 
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
                    {
                        string line;
 
                        while ((line = sr.ReadLine()) != null)
                        {
                            workstations.Add(line);
                        }
                    }
                }
            }

Open in new window

0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 24053500
Hi wally_davis;

The code sample below shows a way of doing what you want.

Fernando
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace ConsoleApplication4
{
    class Program
    {
 
        private static List<string> workstations = new List<string>();
 
        static void Main(string[] args)
        {
            //Check to see if the command line parameter length = 2, one for -f the other the filename
            if (args.Length == 2)
            {
                // Check to see if the parameter is -f
                if (args[0] != "-f")
                {
                    // It was not -f, display message and exit.
                    Console.WriteLine("Input option error, no such option as " + args[0] + " \nHit any key to continue.");
                    Console.ReadLine();
                }
                else
                {
                    // It was -f and now check to see if the file exist
                    if( File.Exists(args[1]) )
                    {
                        // The file was found, fill the workstations list with its values
                        workstations.AddRange(File.ReadAllLines(args[1]));
                    }
                }
            }
            else
            {
                // Invalid number of command line parameters were found
                if (args.Length == 0)
                {
                    Console.WriteLine("Workstation file was NOT provided as an input parameter.");
                }
                else
                {
                    Console.WriteLine("Too many input parameter were provided.");
                }
                Console.Write("Hit any key to cotinue");
                Console.ReadLine();
                return;
            }
 
            // Display Workstation list
            foreach (string ws in workstations)
            {
                Console.WriteLine(ws);
            }
 
            // Keep the application open while I read the screen
            Console.ReadLine();
        }
    }
}

Open in new window

0
 

Expert Comment

by:MarkGMurphy
ID: 24053535
Wally,
I notice you have a "-f" passed as an argument in addition to your filename.  Will you want to identify the filename by argument position?  If not, you can use a switch to identify multiple arguments of different types (i.e. ProofOfConcept /f:true /i:c:\data.txt).
I take it you are passing in a list of machine names or IP addresses you wish to act on in some way.  Please confirm these details and I will reply with some code for you.
Thanks,
Mark
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 

Author Comment

by:wally_davis
ID: 24054207
Hi Carl/Guys, This is almost a done deal.
See code below. The data that is being collected in the "nodeList.Add(node);" List<> Collection is getting lost. I'm passing in a Text file (c:\data.txt) using the Properties\Debug\Command Line arguments section.
In that file are 3 workstations. Everything in the code you provided Carl is great until it gets to the
"if (nodeList.Count > 0)" statement. <-- Right here, there are no workstations stored in the ListArray after it exits the "While" routine. For whatever reason, the values are getting lost. Thanks again for all your help.

if (idx != 1)
            {
                filename = args[idx + 1];
                filename.ToUpper();
 
                if (File.Exists(filename))
                {
                    FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        Program node = new Program();
                        while ((node.NodeToPing = sr.ReadLine()) != null)
                        {
                            nodeList.Add(node);
                        }
                    }
                }
 
 
                if (nodeList.Count > 0)
                {
                    System.Threading.ThreadPool.SetMaxThreads(65, 10);
                    System.Threading.ThreadPool.SetMinThreads(65, 10);
 
                    foreach (Program node in nodeList)
                    {
                        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(PingWorkstations), node.NodeToPing);
                    }
                }
            }

Open in new window

0
 

Author Comment

by:wally_davis
ID: 24054216
Sorry, left the List<> Collections out but its in the code.

List<Program> nodeList = new List<Program>();
List<string> workstations = new List<string>();
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 24054218
Where are you declaring nodeList?
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 24054233
Have you stepped through the code using the debugger to see if it is actually reading anything from the file and adding nodes to the list?
0
 

Author Comment

by:wally_davis
ID: 24054265
yes, I stepped through the code and its storing them there but once out of that WHILE Loop it appears to drop all of the element values.
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 24054378
There must be something odd going on because, as long as the file contains data, there should be something in the list.

You do however have another issue with your code, in that you only instantiate Program once, so each time you set the NodeToPing property and add the node to the List you are in fact altering a single instance and adding it multiple times to the list.

Your loop should be more like the following. Try this first and let us know if the list still says it is empty:


                if (File.Exists(filename))
                {
                    FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            Program node = new Program();     // create a new instance otherwise we'll just be modifying the same object each time
                            node.NodeToPing = line;
     
                            nodeList.Add(node);
                        }
                    }
                }

Open in new window

0
 

Author Closing Comment

by:wally_davis
ID: 31565949
Carl, that made perfect sense and moving the instation called to Program did the trick. The code now works except that the multithreading piece is not working but that's another problem in and of itself.
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

624 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