第一次
自己写的第一个工作中实用的程序。
工具主要是检索目标路径下的所有.sql文件(包括子目录中的文件),然后用正则表达式从各个文件中提取到相应的字符信息。插入到EXCEL文件里。
代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;
namespace Origin
{
class hoho
{
private static ArrayList files = new ArrayList();
//递归查询子目录中的相应文件
public static ArrayList fileR(string filepath, string filter)
{
DirectoryInfo Dir = new DirectoryInfo(filepath);
try
{
foreach (DirectoryInfo d in Dir.GetDirectories())
{
//递归查询子文件夹
fileR(Dir + d.ToString()+"\\", filter);
}
foreach (FileInfo f in Dir.GetFiles(filter))
{
string stemp = Dir + f.ToString();
//Console.WriteLine(stemp);
files.Add(stemp);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return files;
}
//根据传入文件path和名字,返回该内容字符串
public static string workFile(string file)
{
StreamReader reader = null;
reader = new StreamReader(file, System.Text.Encoding.Default);
string str_all = reader.ReadToEnd().Trim();
return str_all;
}
//extract batchName
public static string batchN(string str_all)
{
string str, begin, end;
begin = "@BatchName = '";
end = "'";
Regex reg = new Regex("(?<=(" + begin + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
str = reg.Match(str_all).Value;
return str;
}
//extract fileName
static String fileC(string file)
{
string fileN, begin, end;
begin = "f:";
end = "]";
string filef = file + "]";
Regex reg = new Regex("(?<=(" + begin + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
fileN = reg.Match(filef).Value;
return fileN;
}
static void Main(string[] args)
{
int row = 2;
//Excel comm
Excel.Application app = new Excel.Application();
app.Workbooks.Open("F:\\test\\test.xlsx");
Excel.Worksheet ws = app.Worksheets[1];
try
{
files = fileR("f:\\test\\", "*.sql");
foreach (string file in files)
{
String fileN = "null";
String BatchName = "null";
fileN = fileC(file);
BatchName = batchN(workFile(file));
Console.WriteLine(file);
Console.WriteLine(fileN);
Console.WriteLine(BatchName);
app.Cells[row, 1] = fileN;
app.Cells[row, 2] = BatchName;
//add row in next loop step
row++;
}
app.Visible = true;
app.Workbooks.Close();
app.Quit();
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
finally
{
//kill EXCEL process
System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();
Console.WriteLine(ps);
for (int i = 0; i < ps.Length; i++)
{
if (ps[i].ProcessName.ToUpper() == "EXCEL")
{
ps[i].Kill();
}
}
Console.ReadLine();
}
}
}
}