Solved

Pass a filename to a Console app

Posted on 2009-04-02
11
311 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
I've been searching Microsofts website and there are no really good examples out there unless I'm just overlooking them.
0
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

 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
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.

762 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

8 Experts available now in Live!

Get 1:1 Help Now