Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9006533
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T01:26:11+00:00 2026-06-16T01:26:11+00:00

The below code reads a texts file, formats it, displays any error and insert

  • 0

The below code reads a texts file, formats it, displays any error and insert the data into SQL Server Database. I wrote the below code previously in Visual Basic, now I am trying to rewrite the code int C# but it is not working.

I cannot get the fields indicated to insert into a database: I am trying to get the records without errors to insert into the database even when their are error with other rows.

This was a project I did piece by piece as I am still learning this stuff, so please forgive my ignorance. The database portion seems fine so I did not post it but I can if requested.

Classes from file:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace ConsoleApplication1
{
    class ClsMethods
    {
        public class MemberInfo
        {
            public static string MemberPhone;
            public static string MemberName;
            public static string MemberAddr1;
            public static string MemberAddr2;
            public static string MemberCity;
            public static string MemberState;
            public static string MemberZip;
        }

        public class ErrLog
        {
            public static int RowNum;

            public static List<string> Err;
            public  ErrLog(int row)
            {
                RowNum = row;
                Err = new List<string>();
            }

            public ErrLog()
            {
                Err = new List<string>();
            }
        }
    }
}

MainCode:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        public static class MainModule
        {

           static List<ClsMethods.ErrLog> ErrList;

            public static void Main()
            {
                string strFilename = null;
                FileInfo fiFile = default(FileInfo);
                StreamReader srData = default(StreamReader);
                string strRecord = "";
                List<ClsMethods.MemberInfo> MbrList = default(List<ClsMethods.MemberInfo>);
                ClsMethods.MemberInfo MbrInfo = default(ClsMethods.MemberInfo);
                int successCount = 0;
                int failedCount = 0;
                int totalCount = 0;

                ErrList = new List<ClsMethods.ErrLog>();

                strFilename = "C:\\EMP\\Member.csv";
                fiFile = new FileInfo(strFilename);
                if (fiFile.Exists)
                {
                    if (fiFile.Length > 0)
                    {
                        MbrList = new List<ClsMethods.MemberInfo>();
                        srData = new StreamReader(strFilename);
                        while (srData.Peek() > 0) 
                        {
                            try
                            {
                                strRecord = srData.ReadLine().Replace("\"", "");
                                totalCount = totalCount + 1;
                                String[] rec = strRecord.Split(",".ToCharArray());
                                if ((ValidateRow(rec, totalCount)))
                                {
                                    MbrInfo = new ClsMethods.MemberInfo();
                                    ClsMethods.MemberInfo.MemberPhone = rec[0];
                                    ClsMethods.MemberInfo.MemberName  = rec[1];
                                    ClsMethods.MemberInfo.MemberAddr1 = rec[2];
                                    ClsMethods.MemberInfo.MemberAddr2 = rec[3];
                                    ClsMethods.MemberInfo.MemberCity  = rec[4];
                                    ClsMethods.MemberInfo.MemberState = rec[5];
                                    ClsMethods.MemberInfo.MemberZip   = rec[6];
                                    MbrList.Add(MbrInfo);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("READ: " + ex.Message);
                                srData.Close();
                                srData.Dispose();
                            }
                            Console.WriteLine(strRecord);
                        }
                        foreach (ClsMethods.MemberInfo emp in MbrList)
                        {
                            if ((ClsDatabase.InsertMemberInfo(MbrInfo)))
                            {
                                successCount = successCount + 1;
                            }
                            else
                            {
                                failedCount = failedCount + 1;
                            }
                        }
                        Console.WriteLine("Total rows: {0} ", totalCount);
                        Console.WriteLine("Records without Errors: {0} ", MbrList.Count);
                        Console.WriteLine("Records with errors: {0} ", ErrList.Count);

                        Console.WriteLine("Inserted successfully: " + successCount.ToString());
                        Console.WriteLine("Failed: " + failedCount.ToString());

                        if ((ErrList.Count > 0))
                        {
                            Console.WriteLine("If you want to display errors press D. If you want to store errors in log file press F.");
                            ConsoleKeyInfo cki = default(ConsoleKeyInfo);
                            cki = Console.ReadKey();
                            Console.WriteLine();
                            string res = "";
                            res = cki.Key.ToString(res.ToUpper());

                            if ((res == "D"))
                            {
                                DisplayErrors();
                            }
                            else if ((res == "F"))
                            {
                                WriteErrorsToFile();
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("File " + strFilename + " is empty");
                    }
                }
                else
                {
                    Console.WriteLine("File " + strFilename + " doesn't exists");
                }

                Console.WriteLine("Program End. Press any key to exit");
                Console.ReadKey();
                Environment.Exit(0);
            }
            public static void DisplayErrors()
            {
                foreach (ClsMethods.ErrLog err in ErrList)
                {
                    foreach (string errDescr in ClsMethods.ErrLog.Err)
                    {
                        Console.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
                    }
                }
            }

            public static void WriteErrorsToFile()
            {
                string path = "C:\\Log\\log.txt";
                // Delete the file if it exists.
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                using (StreamWriter outfile = new StreamWriter(File.Create(path)))
                {
                    foreach (ClsMethods.ErrLog err in ErrList)
                    {
                        foreach (string errDescr in ClsMethods.ErrLog.Err)
                        {
                            outfile.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
                        }
                    }
                }
            }

            public static bool ValidateRow(string[] rec, int rowIndex)
            {
                ClsMethods.ErrLog Err = new ClsMethods.ErrLog();
                if ((rec.Length != 7))
                {
                    ClsMethods.ErrLog.Err.Add("Wrong number of values in row");
                }
                else
                {
                    rec[0] = rec[0].Replace("-", "");
                    if ((string.IsNullOrEmpty(rec[0])))
                    {   
                        ClsMethods.ErrLog.Err.Add("Phone is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[1])))
                    {
                        ClsMethods.ErrLog.Err.Add("Name is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[2])))
                    {
                        ClsMethods.ErrLog.Err.Add("Address is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[4])))
                    {
                        ClsMethods.ErrLog.Err.Add("City is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[5])))
                    {
                        ClsMethods.ErrLog.Err.Add("State is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[6])))
                    {
                        ClsMethods.ErrLog.Err.Add("Zip is empty");
                    }
                }
                if ((ClsMethods.ErrLog.Err.Count > 0))
                {
                    ClsMethods.ErrLog.RowNum = rowIndex;
                    ErrList.Add(Err);
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
    }
}

Database Connection and Parameters:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace ConsoleApplication1
{
    class ClsDatabase
    {
        public static SqlConnection GetConnection()
        {
            SqlConnection InitCnt = null;

            InitCnt = new SqlConnection();
            InitCnt.ConnectionString = "Server=MyDB;database=Example;Trusted_Connection=true;";
            try
            {
                InitCnt.Open();
            }
            catch (Exception ex)
            {
                InitCnt.Close();
                InitCnt.Dispose();
            }

            return InitCnt;
        }

        public static bool InsertMemberInfo(ClsMethods.MemberInfo MbrInfo)
        {
            SqlConnection InitCnt = default(SqlConnection);
            SqlCommand InitCmd = default(SqlCommand);

            InitCnt = GetConnection();
            if ((InitCnt != null))
            {
                InitCmd = new SqlCommand();
                InitCmd.Connection = InitCnt;
                InitCmd.CommandText = "uspInsertMemberInformation";
                InitCmd.CommandType = CommandType.StoredProcedure;

                InitCmd.Parameters.Add(new SqlParameter("@MemberPhone", SqlDbType.NVarChar, 10));
                InitCmd.Parameters["@MemberPhone"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberPhone"].Value = ClsMethods.MemberInfo.MemberPhone;

                InitCmd.Parameters.Add(new SqlParameter("@MemberName", SqlDbType.NVarChar, 50));
                InitCmd.Parameters["@MemberName"].Value = ClsMethods.MemberInfo.MemberName;
                InitCmd.Parameters["@MemberName"].Value = ClsMethods.MemberInfo.MemberName;

                InitCmd.Parameters.Add(new SqlParameter("@MemberAddr1", SqlDbType.NVarChar, 30));
                InitCmd.Parameters["@MemberAddr1"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberAddr1"].Value = ClsMethods.MemberInfo.MemberAddr1;

                InitCmd.Parameters.Add(new SqlParameter("@MemberAddr2", SqlDbType.NVarChar, 30));
                InitCmd.Parameters["@MemberAddr2"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberAddr2"].Value = ClsMethods.MemberInfo.MemberAddr2;

                InitCmd.Parameters.Add(new SqlParameter("@MemberCity", SqlDbType.NVarChar, 20));
                InitCmd.Parameters["@MemberCity"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberCity"].Value = ClsMethods.MemberInfo.MemberCity;

                InitCmd.Parameters.Add(new SqlParameter("@MemberState", SqlDbType.NChar, 2));
                InitCmd.Parameters["@MemberState"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberState"].Value = ClsMethods.MemberInfo.MemberState;

                InitCmd.Parameters.Add(new SqlParameter("@MemberZip", SqlDbType.NVarChar, 9));
                InitCmd.Parameters["@MemberZip"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberZip"].Value = ClsMethods.MemberInfo.MemberZip;

                try

                {
                    InitCmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    InitCmd.Parameters.Clear();
                    InitCnt.Close();
                }
            }
            return true;
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T01:26:13+00:00Added an answer on June 16, 2026 at 1:26 am

    Some really peculiar stuff there:

    • ClsMethods contains only classes and is not used; remove it.
    • MemberInfo contains only static fields, so every instance must always contain the same data.
    • ErrLog contains only a static field so, again, every instance will always contain the same data.
    • Main pointlessly sets a bunch of variables to default, which is always null, which is redundant. Why are you doing that?
    • MainModule is also redundant and should be removed.
    • All variables are global, which is unnecessary and risky.
    • MbrInfo = new ClsMethods.MemberInfo(); is useless because all fields are static, you will just be overwriting what is already there.
    • ClsDatabase.InsertMemberInfo(MbrInfo) will always pass the last record as many times as there are records in the file. I’m guessing you want ClsDatabase.InsertMemberInfo(emp). See why globals are bad?
    • InsertMemberInfo ignores the parameter you pass and uses the single static value for every parameter.
    • The default SqlParameter.Direction is Input, you don’t have to reset it.

    I wouldn’t add “Member” to the front to every field; it’s already in the class name. I’m guessing what you want is:

    public class MemberInfo
    {
        public string Phone;
        public string Name;
        public string Addr1;
        public string Addr2;
        public string City;
        public string State;
        public string Zip;
    }
    

    Then in Main you can call:

    MemberInfo mi = new MemberInfo();
    mi.Phone = rec[0];
    mi.Name = rec[1];
    mi.Addr1 = rec[2];
    mi.Addr2 = rec[3];
    mi.City = rec[4];
    mi.State = rec[5];
    mi.Zip = rec[6];
    MbrList.Add(mi);
    

    You use the word Err to refer to a class, the log, and instance variables. This is very confusing. I suggest something like:

    public class ErrLog
    {
        public int RowNum;
        public List<string> Messages;
    
        public ErrLog(int row)
            : base()
        {
            RowNum = row;
        }
    
        public ErrLog()
        {
            Messages = new List<string>();
        }
    }
    

    Your InsertMemberInfo should look more like this:

    var sp = new SqlParameter("@MemberPhone", SqlDbType.NVarChar, 10);
    sp.Value = MbrInfo.whatever;
    InitCmd.Parameters.Add(sp);
    

    Don’t do this:

    try
    {
        InitCmd.ExecuteNonQuery();
    }
     catch (Exception ex)
    {
        return false;
    }
    

    That will discard the reason the procedure failed. Just do this:

    InitCmd.ExecuteNonQuery();
    

    Exceptions. Use them. A few more weird things in your code; start with what I’ve shown.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically the code below reads in a text file and diplays it on the
I have a function(please see code below) which reads some data from the web.
I have a piece of matlab code below which reads data from a table.
I have the below batch that reads data from a text file, the problem
Below i have a code that reads a text file and only writes a
I use the below code to create and read my database in the app
So I have the following code that reads a text file line by line.
I am trying to write a coded that reads in a text file into
I am trying to read a text file using the code (pasted below), but
EXPLANATION OF THE CODE BELOW: I am loading a .txt file and creating a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.