C#调用txt,xml,正则表达式,codesoft打印条码

1. 获取程序安装路径的方法Application.StartupPath

  例如:

  string path = Application.StartupPath + "\\WarterCode.xml";

  就相当于在ASP.NET中的Server.MapPath();

2.操作txt

  (1). 判断文本是否存在,如果不存在则创建文本,向其中写入数据,如果存在,则读取其中的数据

string path = @"C:\WarterCode.txt";
FileInfo fi
= new FileInfo(path);
if (!fi.Exists)
{
//如果不存在,則創建文本
StreamWriter sw = fi.CreateText();
sw.WriteLine(
"0");
sw.Close();
}
else {
//如果存在,則讀取其中的數字型流水碼
StreamReader sr = fi.OpenText();
int wartercode = Convert.ToInt32(sr.ReadLine());
sr.Close();
}

  (2). 判断文本是否存在,如果不存在则创建文本,向其中写入数据,如果存在,直接向其中写入数据

string time = System.DateTime.Now.ToString();
string LabelInfo = Common.CompanyID + Y0 + WW + W + no34 + Common.ModuleID + Common.Version + V;
string LogPath = System.Windows.Forms.Application.StartupPath + "\\Logs\\" + System.DateTime.Now.ToLongDateString() + ".txt";
FileInfo fi
= new FileInfo(LogPath);
StreamWriter sw;
if (!fi.Exists)
{
sw
= fi.CreateText();
}
else {
sw
= new StreamWriter(LogPath,true);//true表示将内容追加在文本的末尾
}
sw.WriteLine(intSSSS
+ "\t" + time + "\t" + LabelInfo);
sw.Close();

3. 操作XML

  向xml中写入数据:

string path = Application.StartupPath + "\\WarterCode.xml";
XmlDocument doc
= new XmlDocument();
doc.Load(path);
XmlNode root
= doc.SelectSingleNode("Root");
XmlNodeList list
= root.SelectNodes("WarterCodeNum");
list.Item(
0).InnerText = wartercode.ToString();
doc.Save(
"WarterCode.xml");

  关于XML在.NET中的运用,参考:http://www.cnblogs.com/JimmyZhang/archive/2008/12/07/1349454.html
4. 调用CodeSoft

  首先添加对CodeSoft安装目录下Lppx2.tlb的引用,再引用命名空间using LabelManager2;

ApplicationClass lbl = new ApplicationClass();

try
{
lbl.Documents.Open(
@"D:label.Lab", false);// 调用设计好的label文件
Document doc = lbl.ActiveDocument;
doc.Variables.FormVariables.Item(
"Var0").Value = txtContent.Text.Trim(); //给参数传值
doc.Variables.FormVariables.Item("Var1").Value = txtContent2.Text.Trim(); //给参数传值

int Num = Convert.ToInt32(txtQuentity.Text); //打印数量
doc.PrintDocument(Num); //打印
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
lbl.Quit();
//退出
}

5. 用正则表达式测试输入格式

  

Regex regex=new Regex(@"^\d+$");
if (!regex.IsMatch(txtPrintNum.Text.Trim())) {
MessageBox.Show(
"數量輸入有誤!");
return;
}

原文地址:https://www.cnblogs.com/johnsmith/p/2182269.html