简体   繁体   English

XML文件错误错误:System.InvalidCastException:指定的强制转换无效

[英]XML File Error Error : System.InvalidCastException: Specified cast is not valid

I am having a problem this is my code`using System; 我有一个问题,这是我的代码使用系统;

namespace cm18b
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(40000);
            Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            string machineID = config.AppSettings.Settings["MachineID"].Value;
            //MessageBox.Show(machineID);
            double time = Convert.ToDouble(config.AppSettings.Settings["time"].Value);
            System.Timers.Timer timer = new System.Timers.Timer(time);
            timer.Elapsed += OnTimer;
            timer.Enabled = true;
            this.WindowState = FormWindowState.Minimized;
        }
        private void OnTimer(object source, ElapsedEventArgs e)
        {
            var timer = (System.Timers.Timer)source;
            timer.Stop();
            //MessageBox.Show("trying");
            BuildTransactionXML();
            timer.Start();
        }
        public bool SendFTP(string file_name)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            String source = config.AppSettings.Settings["sourcelocation"].Value + "/" + file_name; //Change to new file name
            String ftpusername = config.AppSettings.Settings["ftpusername"].Value;
            String ftppassword = config.AppSettings.Settings["ftppassword"].Value;
            String ftpfullpath = config.AppSettings.Settings["ftpurl"].Value + "/" + file_name;
            try
            {
                string filename = Path.GetFileName(source);
                //string ftpfullpath = ftpurl;
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
                ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);

                ftp.KeepAlive = true;
                ftp.UseBinary = true;
                ftp.Method = WebRequestMethods.Ftp.UploadFile;

                FileStream fs = File.OpenRead(source);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                Stream ftpstream = ftp.GetRequestStream();
                ftpstream.Write(buffer, 0, buffer.Length);
                ftpstream.Close();
                return true;
            }
            catch (WebException ex)
            {
                WriteLog(ex);
                return false;


            }
        }
         public void BuildTransactionXML()
        {
            string xmlString = "";
            Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            string transactioncounter = config.AppSettings.Settings["transactioncounter"].Value;
            string BustaA = config.AppSettings.Settings["bagnumber"].Value;

            string cm18string = ConfigurationManager.ConnectionStrings["CM18String"].ConnectionString;
            SqlConnection con = null;
            try
            {
                con = new SqlConnection(cm18string);
                if (con.State != System.Data.ConnectionState.Open)
                {
                    con.Open();
                }
                 string currency = "";
                string device = "";
                string result = "";
                string symbol = "";
                string type = "";
                string type1 = "";
                string file_name = "";
                string user = "";
                string filesaved = "";
                string date = "";
                string time = "";
                string cassette = "";

                SqlCommand cmd = new SqlCommand("SELECT [IDP],[DateTimeOperazione],[Importo],[TipoOperazione],[Banconote_E500],[Banconote_E200],[Banconote_E100],[Banconote_E50],[Banconote_E20],[Banconote_E10],[Banconote_E5],[BustaA] FROM [DataBos].[dbo].[Operazioni] join  [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef where TipoOperazione IN ('161','3', '1') and IDP > @idp", con);
                cmd.Parameters.Add("@idp", transactioncounter);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    string filecounter = config.AppSettings.Settings["filecounter"].Value;

                    switch (rd.GetInt32(3))

                    {
                        case 161:
                            type = "out";
                            type1 = "out";
                            break;
                        case 1:
                            type = "outb";
                            type1 = "outb";
                            break;
                        case 3:
                            type = "in";
                            type1 = "in";
                            config.AppSettings.Settings["bagnumber"].Value = rd.GetString(11);
                            config.Save(ConfigurationSaveMode.Modified);
                            BustaA= rd.GetString(11);
                            break;
                        default:
                            type = "";
                            break;
                    }
                    cassette = BustaA;
                    currency = "Euro";
                    symbol = "€";
                    date = rd.GetDateTime(1).ToString("M/DD/YYYY");
                    time = rd.GetDateTime(1).ToString();
                    device = config.AppSettings.Settings["MachineId"].Value;
                    file_name = device + "_" + type1 + ".xml";
                    xmlString = "";
                    xmlString = "<transaction><device>" + device + "</device><status>" + @type1 + "</status><currency><description>" + currency + "</description><symbol>" + symbol + "</symbol></currency><date_time><date>" + date + "</date><time>" + time + "</time></date_time><cassette>" + cassette + "</cassette><<filename>" + file_name + "</filename>";
                    file_name = device + "_"  + type1 + "_" + filecounter + ".xml";
                   if (type == "in")
                    {
                        config.AppSettings.Settings["HasMoney"].Value = "True";
                        int  ttype = 0; 
                        int  value = 0;
                        int  quantity = 0;
                        for (int i =1 ; i<=7;i++)
                        {
                            ttype = 0;
                            value = 0;
                            quantity = 0;
                            switch(i)
                            {
                                case 1:
                                     ttype = 500;
                                    break;
                                case 2:
                                     ttype = 200;
                                    break;
                                case 3:
                                     ttype = 100;
                                    break;
                                case 4:
                                     ttype = 50;
                                    break;
                                case 5:
                                     ttype = 20;
                                    break;
                                case 6:
                                    ttype = 10;
                                    break;
                                case 7:
                                     ttype = 5;
                                    break;

                            }

                            quantity = rd.GetInt32(i+4);
                            value = quantity * ttype;
                            if(quantity !=0)
                            {
                                xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00").Replace(',', '.') + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00").Replace(',', '.') + "</value></transactionline>";  
                             }
                        }
                    }
                    else if ((type == "out") || ((config.AppSettings.Settings["HasMoney"].Value == "True") && (type == "outb")))
                    {
                        type= "out";
                        config.AppSettings.Settings["HasMoney"].Value = "False";
                        SqlConnection con1 = new SqlConnection(cm18string);
                        if (con1.State != System.Data.ConnectionState.Open)
                        {   
                            con1.Open();
                        }

                        SqlCommand cmd1 = new SqlCommand("SELECT SUM([Banconote_E500]),SUM([Banconote_E200]),SUM([Banconote_E100]),SUM([Banconote_E50]),SUM([Banconote_E20]),SUM([Banconote_E10]),SUM([Banconote_E5])),[BustaA] FROM [DataBos].[dbo].[Operazioni] join  [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef   where TipoOperazione IN ('161','3', '1') and BustaA = @bag group by BustaA", con1);
                        cmd1.Parameters.Add("@bag",cassette);
                        SqlDataReader rd1 = cmd1.ExecuteReader();
                        rd1.Read();
                        long ttype = 0;
                        long value = 0;
                        long quantity = 0;
                        for (int i =1 ; i<=7;i++)
                        {
                            ttype = 0;
                            value = 0;
                            quantity = 0;
                            switch(i)
                            {
                                case 1:
                                     ttype = 5;
                                    break;
                                case 2:
                                     ttype = 10;
                                    break;
                                case 3:
                                     ttype = 20;
                                    break;
                                case 4:
                                     ttype = 50;
                                    break;
                                case 5:
                                     ttype = 100;
                                    break;
                                case 6:
                                     ttype = 200;
                                    break;
                                case 7:
                                     ttype = 500;
                                    break;

                            quantity = rd1.GetInt32(i - 1);
                            value = quantity * ttype;
                            if(quantity !=0)
                            {

                               // xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00").Replace(',', '.') + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00").Replace(',', '.') + "</value></transactionline>";  //Enable for CSExtra
                                xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00") + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00") + "</value></transactionline>";
                            }
                        }
                        rd1.Close();
                        con1.Close();

                    }
                   //else
                    //{
                    //}

                    xmlString = xmlString + "</transaction>";

                    string fout = config.AppSettings.Settings["destinationlocation"].Value;
                    System.IO.StreamWriter file = new System.IO.StreamWriter(fout + "\\"+ file_name);
                    file.WriteLine(xmlString);
                    file.Close();
                    if (SendFTP(file_name))
                    {
                        config.AppSettings.Settings["transactioncounter"].Value = rd.GetInt32(0).ToString();
                        transactioncounter = rd.GetInt32(0).ToString();
                        config.Save(ConfigurationSaveMode.Modified);
                        config.AppSettings.Settings["filecounter"].Value = Convert.ToInt32(config.AppSettings.Settings["filecounter"].Value) + 1 + "";
                        filecounter = config.AppSettings.Settings["filecounter"].Value;
                        config.Save(ConfigurationSaveMode.Modified);
                        WriteLog(file_name);
                    }
                    else
                    {
                        break;
                    }
                }
                rd.Close();
                con.Close();
            }}
            catch (Exception e)
            {
                WriteLog(e);
            }{
        }}

   public void WriteLog(string message)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
                System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);

                file1.WriteLine();
                file1.WriteLine("Successfully completed");
                file1.WriteLine(message);
                file1.WriteLine("==================================================================================================");
                file1.WriteLine("==================================================================================================");
                file1.WriteLine();
                file1.Close();
            }
            catch
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
            }
        }

        public void WriteLog(WebException ex)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
                System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
                file1.WriteLine();
                file1.WriteLine("FTP Error");
                file1.WriteLine("Error : " + ex.ToString());
                file1.WriteLine("FTP Response : " + ((FtpWebResponse)ex.Response).StatusDescription);
                file1.WriteLine("FileCounter : " + config.AppSettings.Settings["filecounter"].Value);
                file1.WriteLine("==================================================================================================");
                file1.WriteLine("==================================================================================================");
                file1.WriteLine();
                file1.Close();
            }
            catch
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
            }
        }

        public void WriteLog(Exception ex)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
                System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
                file1.WriteLine();
                file1.WriteLine("XML File Error");
                file1.WriteLine("Error : " + ex.ToString());
                file1.WriteLine("FileCounter : " + config.AppSettings.Settings["filecounter"].Value);
                file1.WriteLine("==================================================================================================");
                file1.WriteLine("==================================================================================================");
                file1.WriteLine();
                file1.Close();
            }
            catch
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
            }
        }
    }
}

It is giving me the error at line quantity = rd.GetInt32(i+4) 它给我行quantity = rd.GetInt32(i+4)

I know the value is int 32 only from a database so why mi getting this error.? 我知道值仅是来自数据库的int 32,所以为什么mi会收到此错误。

     `

It is probably because i+4 isn't a Int32 datatype. 可能是因为i+4不是Int32数据类型。 Trying printing the i+4 before and check what is the column type that matches in that position and fix your code accordingly. 尝试先打印i+4 ,然后检查在该位置匹配的列类型,然后相应地修复代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:GetCharacters System.InvalidCastException:指定的强制类型转换无效的服务器 - Error: GetCharacters System.InvalidCastException: Specified cast is not valid server System.InvalidCastException:指定的强制转换无效。错误 - System.InvalidCastException: Specified cast is not valid. Error 消息错误:System.InvalidCastException:指定的强制转换无效10 - Message error : System.InvalidCastException: Specified cast is not valid 10 Linq To数据集错误System.InvalidCastException:指定的强制转换无效 - Linq To Data set error System.InvalidCastException: Specified cast is not valid 指定的转换无效-System.InvalidCastException - Specified cast is not valid - System.InvalidCastException System.InvalidCastException:指定的强制转换无效 - System.InvalidCastException: Specified cast is not valid “ System.InvalidCastException:指定的转换无效”-DateTime - “System.InvalidCastException: Specified cast is not valid” - DateTime System.InvalidCastException:指定的强制转换在.ExecuteScalar上无效 - System.InvalidCastException: Specified cast is not valid at .ExecuteScalar System.InvalidCastException:&#39;指定的强制转换无效。 - System.InvalidCastException: 'Specified cast is not valid.' C#请求处理程序错误System.InvalidCastException:指定的强制转换无效 - C# REQUEST HANDLER ERROR System.InvalidCastException: Specified cast is not valid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM