1. 读写文件操作
using (file = new System.IO.StreamReader(inputfile))
{
using (outfile = new System.IO.StreamWriter(outputfile))
{
try
{
while ((line = file.ReadLine()) != null)
{
/// do something
}
}
catch (Exception e)
{
...
}
}
}
2. 文件及文件夹的相关API
得到文件当前目录: string fileDir = System.IO.Path.GetDirectoryName(fileName);
得到当前文件的名称 System.IO.Path.GetFileNameWithoutExtension(fileName)
判断文件是否存在: System.IO.File.Exists(fileName)
判断文件夹是否存在: Directory.Exists(directory)
删除文件夹及子目录: Directory.Delete(directory, true);
新建文件夹: Directory.CreateDirectory(directory);
得到当前文件夹的所有子文件夹: System.IO.Directory.GetDirectories(directory)
得到当前文件夹下所有文件: System.IO.Directory.GetFiles(directory)
得到文件夹信息: DirectoryInfo di = new DirectoryInfo(fileDir);
文件夹的名字: di.Name
文件夹的上级文件夹名字: di.Parent.Name
得到文件的相关信息: FileInfo fileInfo = new FileInfo(fileName);
得到文件大小: fileInfo.Length
得到文件最后修改时间:fileInfo.LastWriteTimeUtc
3. 多线程的lock
public class TestMonitor
{
/// <summary>
/// lock
/// </summary>
private readonly object mlock = new object();
/// <summary>
/// test lock
/// </summary>
public void TestStatus()
{
bool taken = false;
try
{
Monitor.Enter(mlock, ref taken);
/// do something
}
finally
{
if (taken == true)
{
Monitor.Exit(mlock);
}
}
}
}
4. 程序中配置一个计时器类(Monitor),用于做运行时间测算:
this.beginTime = DateTime.UtcNow;
this.endTime = DateTime.UtcNow;
this.duration = this.endTimeSpan.Subtract(this.beginTime);
5. 程序中配置一个日志类(Logger),用于记录程序运行异常及输出,而且最好可以把Logger类设置成统一接口,用于console和文本日志的输出
Logger.WriteLine(string, msgTag);
6. 字符串常量定义在前面,const或readonly
7. 项目中要有一个common settings 类,用于设置程序的各种参数值,Application.Properties.Settings.Default.xxx
8. SqlClient数据库总结:
1. Insert:
try
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = @"insert table values (@Test);";
cmd.Parameters.AddWithValue("@Test", "testData");
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
throw e;
}
2. Build Connection String:
SqlConnectionStringBuilder connStringBuilder;
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = this.dataSource;
connStringBuilder.InitialCatalog = this.databaseName;
connStringBuilder.Encrypt = true;
connStringBuilder.TrustServerCertificate = false;
connStringBuilder.UserID = this.userName;
connStringBuilder.Password = this.password;
this.connectionString = connStringBuilder.ToString();
3. Query:
SqlDataReader reader;
DataTable result = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
SqlCommand command = new SqlCommand(sqlcommand, conn);
reader = command.ExecuteReader();
result.Load(reader);
}
}
}
catch (Exception e)
{
throw e;
}
4. 最好建立一个通用的接口,可以给不同的应用使用同一个接口,比如insert的接口,需要统一。