次のコードは、テキストファイルを読み取り、フォーマットし、エラーを表示して、SQLServerデータベースにデータを挿入します。以前にVisualBasicで以下のコードを記述しましたが、コードint C#を書き直そうとしていますが、機能しません。
データベースに挿入するように示されたフィールドを取得できません。他の行でエラーが発生している場合でも、エラーなしでレコードを取得してデータベースに挿入しようとしています。
これは私がまだこのことを学んでいるので、私が少しずつ行ったプロジェクトでした、それで私の無知を許してください。データベース部分は問題ないようですので、投稿しませんでしたが、リクエストがあれば投稿できます。
ファイルからのクラス:
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;
}
}
}
}
}
データベース接続とパラメータ:
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;
}
}
}