1 服务程序系统日志方法
private void Log(string msg) //log文件夹里每天创建txt文本日志
{
string dir = MySQLHelper.GetFilePath("log/");
string fileName = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = null;
StreamWriter sw = null;
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
try
{
//实例化一个文件流--->与写入文件相关联
fs = new FileStream(fileName, FileMode.OpenOrCreate);
fs.Seek(0, SeekOrigin.End);
//实例化一个StreamWriter-->与fs相关联
sw = new StreamWriter(fs);
msg = "[" + DateTime.Now.ToString("HH:mm:ss") + "]:" + msg;
sw.WriteLine(msg);
}
catch
{
//do nothing
}
finally
{
if (sw != null)
{
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
}
if (fs != null)
fs.Close();
}
}
2 C#调用C++DLL方法,返回结构体指针
引用命名空间:using System.Runtime.InteropServices;
声明方法如下:
[DllImport("XX.dll")]
public static extern int dllfangfa(IntPtr d);
C++DLL里的结构体如下:
#define num 960
struct jgt
{
int cshu1[num];
int cshu2;
char cshu3;
float cshu4;
};
C#中定义如下:
public const int num = 960;
[StructLayout(LayoutKind.Sequential)] //关键处
public struct jgt
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 960)] //关键处
public int[] cshu1;
public int cshu2;
public char cshu3;
public float cshu4;
};
jgt s = new jgt();
IntPtr intptr = Marshal.AllocHGlobal(Marshal.SizeOf(s)); //定义一个指针
Marshal.StructureToPtr(s, intptr, true); //将结构体放入指针
dllfangfa(s);//调用dll里的方法
s = (jgt)Marshal.PtrToStructure(intptr, typeof(jgt)); //最关键处,差点因为这句代码而放弃。因为你把结构体封装成指针传过去了,回来之后当然得解封才能得到值。
3 VS2008工程访问sql server数据库
首先把web.config文件里的<connectionStrings/>标签改为:
<connectionStrings>
<add name="nihao" connectionString="data source=服务器名; initial catalog=数据库名;Integrated Security=SSPI"/>
</connectionStrings>
再添加引用:using System.Data.SqlClient;
然后编写代码:
ConnectionStringSettings setings = ConfigurationManager.ConnectionStrings["nihao"];
string str = setings.ConnectionString;
SqlConnection conn = new SqlConnection(str);
string sql = "select * from student";
SqlCommand comm = new SqlCommand(sql, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
4 C#实现多语言控制
首先右击工程-添加-添加ASP.NET文件夹-选择App_GlobalResources。
在该文件夹里添加Resource1.resx默认资源文件,再添加Resource1.zh-hk.resx和Resource1.en-us.resx,注意三个文件夹的属性都设为嵌入的资源。
在登录系统的时候设置语言种类的Session,Session["Culture"] = "zh-cn";(zh-cn:中文简体,zh-hk:中文繁体,en-us:英文)
进去系统之后根据语言种类的Session设置要使用的资源文件:
string currentCulture = (string)Session["Culture"];
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(currentCulture);
这样还有一个问题,就是每个页面都要添加上面两行代码,为此我们在工程里添加一个公共类,所有页面都继承他。
既然所有页面继承他,那么他必须继承页面:System.Web.UI.Page
public class PageBase : System.Web.UI.Page
{
public PageBase()
{
}
protected override void InitializeCulture()
{
string currentCulture = (string)Session["Culture"];
if (string.IsNullOrEmpty(currentCulture))
{
currentCulture = "zh-cn";
}
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(currentCulture);
}
}