开发者

Windows IO Error

开发者 https://www.devze.com 2023-02-20 01:02 出处:网络
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Configuration;
using System.Collections;
using System.Timers;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Net.Mail;


namespace VSATStatusReader
{
    class Program
    {
        static void Main(string[] args)
        {
            //Modified 开发者_Go百科by Reema for generating log in table and trigger mail on success or failure of this utility on 16-feb-2011.
                try
                {
                    InsertIntoJobLogTable("Utility Started", "S");
                    UtilityMainFunction();
                }
                catch (Exception ex)
                {
                    InsertIntoJobLogTable("Error on returning from UtilityMainFunction function: '" + ex.Message + "' ", "E");
                    UtilityRunMailToProMonSys("0", "'" + ex.Message + "'", "", "");
                }
        }

        public static void UtilityMainFunction()
        {
            DataSet ds;
            string IP = "";

            ds = new DataSet();

            try
            {
                ds = getDataSet("select gateway_ip as IP from shannonnew..gateway_info").Copy();

                foreach (DataRow dRow in ds.Tables[0].Rows)
                {
                    IP = dRow["IP"].ToString();

                    CreateRunBatchFile(IP);

                    string[] DNCCfileEntries = Directory.GetFiles("c:/VSATStatus/VSATStatusFiles");
                    string connString = getConnString();
                    SqlConnection myDbConnection = new SqlConnection(connString);
                    myDbConnection.Open();

                    foreach (string fileName in DNCCfileEntries)
                    {
                        FileStream file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);

                        StreamReader sr = new StreamReader(file);

                        ArrayList finalWordList;

                        string s = sr.ReadToEnd();
                        string[] lines = Regex.Split(s, "\r\n");

                        foreach (string line in lines)
                        {
                            string formatedLine = line.Replace("iso.3.6.1.4.1.303.3.3.19.6.3.25.1.3.", "");
                            string[] words = formatedLine.Split(' ');
                            finalWordList = new ArrayList();
                            if (words[0].ToString() != "")
                            {
                                finalWordList.Add(words[0]);
                                finalWordList.Add(words[1]);

                                //Database Insert Code here
                                if (line.Trim() != "")
                                {
                                    string strCmd = "Insert into ipgw_evp (Serial_No, VSAT_Status, Gateway_IP) values ('" + finalWordList[0] + "', '" + finalWordList[1] + "', '" + IP + "')";
                                    SqlCommand command = new SqlCommand(strCmd, myDbConnection);
                                    command.ExecuteNonQuery();
                                }
                            }
                        }
                        sr.Close();
                        file.Close();
                    }
                    myDbConnection.Close();
                }
                InsertIntoJobLogTable("Utility Ended", "C");
                //UtilityRunMailToProMonSys("1", "success", "");
            }
            catch (Exception ex)
            {
                InsertIntoJobLogTable("Error in UtilityMainFunction:'" + ex.Message + "' ", "F");
                UtilityRunMailToProMonSys("0", "'" + ex.StackTrace.ToString() + "'", "'" + IP + "'", "'" + ex.Message + "'");
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
        }

        private static string getConnString()
        {
            string connectionProperties = ConfigurationSettings.AppSettings["ProMonSysConsoleString"];
            return connectionProperties;
        }

        public static void CreateRunBatchFile(string IP)
        {
            //change the path as required
            string filepath = "c:/VSATStatus\\VSATStatus.bat";

            try
            {
                StreamWriter sw = File.CreateText(filepath);

                sw.WriteLine("del C:\\VSATStatus\\VSATStatusFiles\\VSATStatus.txt");
                sw.WriteLine("@echo off");
                sw.WriteLine("Snmpwalk -v 1 -O q -c public " + IP + " 1.3.6.1.4.1.303.3.3.19.6.3.25.1.3 >>C:\\VSATStatus\\VSATStatusFiles\\VSATStatus.txt");
                sw.Close();

                Process p = null;

                string targetDir;
                targetDir = string.Format(@"C:\VSATStatus");
                p = new Process();
                p.StartInfo.WorkingDirectory = targetDir;
                p.StartInfo.FileName = "VSATStatus.bat";
                p.StartInfo.Arguments = string.Format("C-Sharp Console application");
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
        }

        public static DataSet getDataSet(string strCmd)
        {
            SqlCommand command;
            SqlDataAdapter da;
            DataSet ds;

            string connString = getConnString();
            SqlConnection myDbConnection = new SqlConnection(connString);
            myDbConnection.Open();

            command = new SqlCommand(strCmd, myDbConnection);
            command.CommandType = CommandType.Text;
            da = new SqlDataAdapter(command);
            ds = new DataSet();
            da.Fill(ds);

            myDbConnection.Close();

            return ds;
        }

        //changed by Reema for sending massage and stacktrace in mails.
        public static void UtilityRunMailToProMonSys(string str, string stacktr, string IP, string error)
        {
            try
            {
                string msg = "";
                msg += "<BR>";
                if (str == "0")
                {
                    msg += "VSATStatusReader Utillity fails.";
                    msg += "<BR>";
                    msg += "<BR>Failed IP Gateway is : '" + IP + "' ";
                    msg += "<BR>";
                    msg += "<BR>";
                    msg += "Exception is : '" + error + "' ";
                    msg += "<BR>";
                    msg += "<BR>";
                    msg += "'" + stacktr + "'"; 
                    msg += "<BR>";
                }
                //else
                //{
                //    msg += "VSATStatusReader Utility run successfully. ";
                //}
                msg += "<BR>";
                msg += "<BR>Regards,";
                msg += "<BR>ProMonSys Admin";
                msg += "<BR>";
                var message = new MailMessage(ConfigurationSettings.AppSettings["DefaultEmail"], ConfigurationSettings.AppSettings["ToMail"])
                {
                    Subject = " ProMonSys VSATStatusReader Utility Status",
                    Body = msg,
                    IsBodyHtml = true
                };

                var client = new SmtpClient(ConfigurationSettings.AppSettings["MailServer"]);
                client.Send(message);
            }
            catch (Exception ex)
            {

            }
        }


        public static void InsertIntoJobLogTable(string Msg, string MsgType)
        {
            SqlCommand Cmd = new SqlCommand();
            SqlConnection Conn = new SqlConnection(ConfigurationSettings.AppSettings["ProMonSysConsoleString"]);
            try
            {

                if (Msg.Length > 8000)
                {
                    Msg = Msg.Substring(0, 7999);
                }
                else if (Msg.IndexOf("'") >= 0)
                {
                    Msg = Msg.Replace("'", "");
                }

                Cmd.Connection = Conn;
                Cmd.CommandType = CommandType.StoredProcedure;
                Cmd.CommandText = "Create_Job_Utility_Log_SP";
                Cmd.Parameters.Clear();
                Cmd.Parameters.Add("@vcJobName", "VSATStatusReader_Utility");
                Cmd.Parameters.Add("@vcModule", "ProMonSys");
                Cmd.Parameters.Add("@dtType", MsgType);
                Cmd.Parameters.Add("@vcJobType", "U");
                Cmd.Parameters.Add("@vcDBUsed", "VSATStatusProgram, ProMonSys");
                Cmd.Parameters.Add("@vcJobStatus", Msg);
                Conn.Open();
                Cmd.ExecuteNonQuery();
                Conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
            finally
            {
                Conn.Dispose();
                Cmd.Dispose();
            }

        }
    }

    //public class MailHelper
    //{
    //    public static void SendMailMessage(string from, string to, string bcc, string cc, string subject, string body)
    //    {
    //        MailMessage mMailMessage = new MailMessage();
    //        mMailMessage.From = new MailAddress(from);
    //        mMailMessage.To.Add(new MailAddress(to));

    //        if ((bcc != null) && (bcc != string.Empty))
    //        {
    //            mMailMessage.Bcc.Add(new MailAddress(bcc));
    //        }
    //        if ((cc != null) && (cc != string.Empty))
    //        {
    //            mMailMessage.CC.Add(new MailAddress(cc));
    //        }
    //        mMailMessage.Subject = subject;            
    //        mMailMessage.Body = body;

    //        mMailMessage.IsBodyHtml = true;
    //        mMailMessage.Priority = MailPriority.Normal;

    //        SmtpClient mSmtpClient = new SmtpClient();
    //        mSmtpClient.Send(mMailMessage);
    //    }
    //}


}

Here is my code..This code runs fine on my previous server which is configured on Windows 2008 but when i want to try to run this code in Windows 2003, then sometimes it is running but sometimes it is giving this exception :

Exception is : ''Access to the path 'c:\VSATStatus\VSATStatusFiles\VSATStatus.txt' is denied.''

'' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) at VSATStatusReader.Program.UtilityMainFunction() in C:\Inetpub\wwwroot\VSATStatusReader\VSATStatusReader\Program.cs:line 61''


Does the path exist and do you have permissions to write to it? From the fact that you have wwwroot floating around the exception check that the service account you are using has write permissions to C:\VSATStatus\VSATStatusFiles.


I believe this is because the textfile is being used. Either you do not close it properly while you are debugging / testing. Or it is being used by another program.

0

精彩评论

暂无评论...
验证码 换一张
取 消