Solved

Pass a filename to a Console app

Posted on 2009-04-02
11
312 Views
Last Modified: 2013-12-17
I want to pass in a file called "data.txt" to a console application as an argument.
Which class do you use? Environment , Process or ProcessStartInfo and could some give me an example of how to write that code to pass it in?
I want to be able to get that text passed in and then store it in an Array and add each workstation to "nodeList.Add(node)". See code below.
I would be most grateful,
Thanks,
Wally
List<Program> nodeList = new List<Program>();

List<string> workstations;
 

if (args.Length > 0)

            {

                // Load command line arg into List<string> collection

                // assuming comma-seperated values

                workstations = new List<string>(args[0].Split(new char[] { ',' }));

                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
  • 6
  • 4
11 Comments
 
LVL 6

Expert Comment

by:HarryNS
ID: 24051043
You mean something like this,

ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "WINWORD.EXE";
        startInfo.Arguments = f;
        Process.Start(startInfo);
0
 

Author Comment

by:wally_davis
ID: 24051083
No, actually, not start an Application, but, pass in a txt file that would contain say "20" workstation names. So, I want to pass in a txt file to be used within the Consol application.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 24051161
You can't pass an actual file. You would need to pass the contents of the file, or a path to the file and let the app open it itself.
0
 

Author Comment

by:wally_davis
ID: 24051191
Ok, lets see if I can explain this better. Instead of having the filename coded into the Console application,
I would like to run the Console application, call it "ProofOfConcept.exe". What I would like to do is have a "-f" switch (-f stands for filename) and then the name of the file to it.
So, If I want to pass in "data.txt" file, I would like the program to work like this:
ProofOfConcept -f data.txt.
Hopefully that makes more sense.
0
 

Author Comment

by:wally_davis
ID: 24051220
I've been searching Microsofts website and there are no really good examples out there unless I'm just overlooking them.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 52

Expert Comment

by:Carl Tawn
ID: 24051257
Try this:
static void Main(string[] args)

{

    int idx = Array.IndexOf(args, "-f");

    string filename = "";
 

    if (idx != -1)

    {

        filename = args[idx + 1];

    }

}

Open in new window

0
 

Author Comment

by:wally_davis
ID: 24051580
ok, Carl, The code ran but it didn't send the three workstations to the database with ping results I was expecting. My data.txt file contains these three workstations (no commas in the text file): C001617259BA7, C001E371E21B2 and C001422C95811. Think I'm going to need a little more help sorting it out. Here's what I have for code below. Its around 200 lines and if pasted into Word/Landscape, its pretty straightforward. Thanks.
using System;

using System.Collections.Generic;

using System.Net;

using System.Net.NetworkInformation;

using System.Data.SqlClient;

using System.Diagnostics;
 

namespace ProofOfConcept

{

    class Program

    {

        // This is not used at the moment... but may be...

        static void UpdateDatabase(Object database)

        {
 

        }
 

        // The threadpool's threads call this with the argument "new "String( node.NodesToPing)" 

        // that is passed to QueueUserWorkItem and so, each computer is pinged quickly in the

        // PingWorkstations() method when added to the threadpool.

        static void PingWorkstations(Object threadContext)

        {

            String computer = (String)threadContext;

            // PingThreadContext pc = (PingThreadContext)threadContext;

            

            string status = "";

            string epAddress = "";
 

            SqlConnection conn = new SqlConnection(SettingsManager.ConnectionString);

            SqlCommand sqlCmd = new SqlCommand("usp_PingStatus", conn);

            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
 

            try

            {   

                // Verify host is in DNS first

                IPHostEntry IPHost = Dns.GetHostEntry(computer);
 

                // Ping the workstation, get status and update DB

                foreach (IPAddress address in IPHost.AddressList)

                {

                    Ping p = new Ping();
 

                    try

                    {

                        // Based on the Ping Status will determine which

                        // case to process.

                        PingReply pr = p.Send(computer);

                        switch (pr.Status)

                        {

                            case IPStatus.Success:

                                sqlCmd.Parameters.AddWithValue("Status", "Reachable");

                                sqlCmd.Parameters.AddWithValue("Endpoint", computer);

                                sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() : 

                                                                IPAddress.None.ToString());

                                sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
 

                                status = "Reachable";

                                epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();

                                //Console.WriteLine(computer + " - Sweet");

                                break;

                            case IPStatus.TimedOut:

                                sqlCmd.Parameters.AddWithValue("Status", "Timed Out");

                                sqlCmd.Parameters.AddWithValue("Endpoint", computer);

                                sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :

                                                                IPAddress.None.ToString());

                                sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
 

                                status = "Timed Out";

                                epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();

                                //Console.WriteLine(computer + " - Timedout");

                                break;

                            case IPStatus.DestinationHostUnreachable:

                                sqlCmd.Parameters.AddWithValue("Status", "Host Unreachable");

                                sqlCmd.Parameters.AddWithValue("Endpoint", computer);

                                sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :

                                                                IPAddress.None.ToString());

                                sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
 

                                status = "Host Unreachable";

                                epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();

                                //Console.WriteLine(computer + " - Timedout");

                                break;

                            case IPStatus.DestinationNetworkUnreachable:

                                sqlCmd.Parameters.AddWithValue("Status", "Network Unreachable");

                                sqlCmd.Parameters.AddWithValue("Endpoint", computer);

                                sqlCmd.Parameters.AddWithValue("IPAddress", (address != null) ? address.ToString() :

                                                                IPAddress.None.ToString());

                                sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);

                                status = "Network Unreachable";

                                epAddress = (address != null) ? address.ToString() : IPAddress.None.ToString();

                                break;

                            case IPStatus.Unknown:

                                sqlCmd.Parameters.AddWithValue("Status", "unknown");

                                sqlCmd.Parameters.AddWithValue("Endpoint", computer);

                                sqlCmd.Parameters.AddWithValue("IPAddress", "NA");

                                sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
 

                                status = "unknown";

                                epAddress = "NA";

                                break;

                        }

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine("Error occurred: " + ex.Message);

                    }
 

                    //Open a DB connection.... SEND THE DATA CLOSE IT
 

                    try

                    {

                        // Lets add the data to the DB

                        conn.Open();

                        sqlCmd.ExecuteNonQuery();

                        Console.WriteLine("EP Status : {0} \nEP Name: {1} \nEP Address: {2}\n", status, computer, address );

                    }

                    catch

                    {

                    }

                    finally

                    {

                        conn.Close();

                    }

                }

            }

            // If no DNS Record exists then update

            // Endpoint information in nodes table

            catch

            {
 

                sqlCmd.Parameters.AddWithValue("Status", "No DNS Record");

                sqlCmd.Parameters.AddWithValue("Endpoint", computer);

                sqlCmd.Parameters.AddWithValue("IPAddress", "NA");

                sqlCmd.Parameters.AddWithValue("DTStamp", DateTime.Now);
 

                status = "No DNS Record";

                epAddress = "NA";
 

                conn.Open();

                sqlCmd.ExecuteNonQuery();

                Console.WriteLine("EP Status : {0} \nEP Name: {1} \nEP Address: {2}\n", status, computer, epAddress);

                conn.Close();
 

            }

        }
 

        /* When availThreads = maxThreads the 

         * entire ThreadPool has completed being

         * processed and a Sleep of 1 second before

         * the next ThreadPool starts processing

         */

        static void WaitForPool()

        {

            int maxThreads = 0;

            int placeHolder = 0;

            int availThreads = 0;

            while (true)

            {

                System.Threading.ThreadPool.GetMaxThreads(out maxThreads, out placeHolder);

                System.Threading.ThreadPool.GetAvailableThreads(out availThreads, out placeHolder);

                if (availThreads == maxThreads) break;

                System.Threading.Thread.Sleep( 1000 );                

            }
 

            return ;

        }

        /* -----------------------------   Main () Program entry ------------------------------ */
 

        // This is the Collection List property

        // that will hold each workstation value

        // that will eventually get pinged.

        public string nodeToPing;

        public string NodeToPing

        {

            get { return nodeToPing; }

            set { nodeToPing = value; }

        }
 
 

        static void Main(string[] args)

        {
 

            // Do Database Query Here.....

            // This will hold the entire workstation 

            // list that is pulled from the Nodes table

            List<Program> nodeList = new List<Program>();

            List<string> workstations;
 

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

                }
 

            }
 

                if (nodeList.Count > 0)

                {

                    // parameters( max # of worker threads in thread

                    // pool and max # asynchronous IO threads in pool)

                    System.Threading.ThreadPool.SetMaxThreads(65, 10);

                    System.Threading.ThreadPool.SetMinThreads(65, 10);
 

                    /* For each computer in the computer list,

                     * each computer to be pinged by the PingWorkstations()

                     * method gets passed to the QueueUserWorkItem to be

                     * processed by the threadpool thread. 

                     * Each workstation to be pinged gets added to the pool

                     * and processed quickly.

                     */

                    foreach (Program node in nodeList)

	                {

                		System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(PingWorkstations), node.NodeToPing );

	                }

                }
 

                /* This little baby is the "ShamWow" it waits till all those threads in the threadpool 

                * are done... and you will say "Wow" everytime.

                * It's made in Germany, lol. This method processes and completes each threadpool before 

                * moving onto the next threadpool.

                */

                WaitForPool();

            }

        }

    }

Open in new window

0
 

Author Comment

by:wally_davis
ID: 24051594
I retyped in the Command Prompt "ProofOfConcept.exe -f c:\data.txt and still no data was updated in DB.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 24051988
Your not actually reading the file. You are passing a file name to the app but just trying to split it as if it were a comma-seperated list, like in your previous posting.
0
 

Author Comment

by:wally_davis
ID: 24052508
Ok, looks like I overlooked that part. So, since I've passed the filename in, can I open it and read the data in?
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 24053462
Yes, obviously you would need to check that the filename passed is valid before doing anything with it. But assuming it is valid and it stores one workstation per line then you can use something like:
            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

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

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

920 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

16 Experts available now in Live!

Get 1:1 Help Now