c#读取文件夹下文件的名称,名称按下划线分开,将名称写入Oracle数据库
private void timer1_Tick(object sender, EventArgs e)
{
listBox1.Items.Clear();
label2.Text = "定时器正在运行...";
DirectoryInfo theFolder = new DirectoryInfo(textBox1.Text);
FileInfo[] dirInfo = theFolder.GetFiles();
//遍历文件夹
foreach (FileInfo NextFolder in dirInfo)
{
//遍历文件
listBox1.Items.Add(NextFolder.Name);
}
//读取listBox1里的数据,按下划线分开,导入到数据库
int i;
i = listBox1.Items.Count;
for (int j = 0; j < i; j++)
{
string str = listBox1.Items[j].ToString();
//string path = @"E:\test\testdata\" + str + "";
//string path2 = @"E:\test\backdata\" + str + "";
//FileStream fileStream = File.OpenRead(path);
OracleConnection conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=**.**.**.**)(PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=TEST)));Persist Security Info=True;User ID=TEST;Password=TEST;");
//StreamReader reader = new StreamReader(fileStream);
conn.Open();
//向数据库插入数据
OracleCommand command = conn.CreateCommand();
command.CommandText = "insert into TABLE(ID,QRCODE,PRODUCTPN,STATUS,DATETIME) values (:ID,:QRCODE,:PRODUCTPN,:STATUS,:DATETIME)";
//string line = null;
//while ((line = reader.ReadLine()) != null)
//{
string ictid = Guid.NewGuid().ToString();
DateTime datetime = DateTime.Now;
//string[] str1 = str.Split('_'); 单字符切割
string[] str1 = str.Split(new Char[]{'_','.'}); //多字符切割
string qrcode = str1[0];
string pn = str1[1];
string sta = str1[2];
command.Parameters.Clear(); //每次插入都要清除参数
command.Parameters.Add(new OracleParameter(":ID", ictid));
command.Parameters.Add(new OracleParameter(":QRCODE", qrcode));
command.Parameters.Add(new OracleParameter(":PRODUCTPN", pn));
command.Parameters.Add(new OracleParameter(":STATUS", sta));
command.Parameters.Add(new OracleParameter(":DATETIME", datetime));
//int tem=command.ExecuteNonQuery();
if (command.ExecuteNonQuery() > 0)
{
richTextBox1.Text += "\n1条数据保存成功";
}
//}
//fileStream.Close();
//reader.Close();
conn.Close();
command.Dispose();
//插入数据成功后,删除文件
//File.Delete(textBox1.Text);
//richTextBox1.Text += "\ntextBox1.Text删除成功";
if (!Directory.Exists(@"E:\test\backdata"))
{
Directory.CreateDirectory(@"E:\test\backdata");
}
string path = @"E:\test\testdata\" + str + "";
string path2 = @"E:\test\backdata\" + str + "";
FileInfo fi1 = new FileInfo(path);
FileInfo fi2 = new FileInfo(path2);
try
{
// Create the source file.
// using (FileStream fs = fi1.Create()) { }
//Ensure that the target file does not exist.
if (File.Exists(path2))
{
fi2.Delete();
}
//Copy the file.f
fi1.CopyTo(path2);
richTextBox1.Text += String.Format("\n{0} 复制到 {1}.", path, path2);
File.Delete(path);
richTextBox1.Text += String.Format("\n{0}文件删除成功",path);
}
catch (IOException ioex)
{
richTextBox1.Text += String.Format("报错信息:{0}", ioex.Message);
}
}
label2.Text = "定时器停止...";
}