c#小知识

来源:互联网 发布:台达plc编程实例 编辑:程序博客网 时间:2024/06/05 09:16

1.xml

XmlDocument xmldoc = new XmlDocument();        xmldoc.Load(url); // url可以使本地路径,也可以是网络路径下面以一个简单的xml为例:<?xml version="1.0"?> <message xmlns="http://www.mydomain.com/MyDataFeed" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation="http://www.mydomain.com/MyDataFeed https://secure.mydomain/MyDataFeed/myDataFeed.xsd" requestId="13898" status="1"> <error>Invalid Login</error> </message>     下面尝试读取error节点的内容XmlNode errorNode = xmldoc.SelectSingleNode("/message/error"); if (errorNode != null) Console.Writeline("There is an error");     返回的结果一直为Null     产生这个问题的原因就在于上面的xml文档中使用了命名空间,当xml中定义了命名空间时,在查找节点的时候需要使用下面的方法XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmldoc.NameTable); nsMgr.AddNamespace("ns", "http://www.mydomain.com/MyDataFeed");XmlNode errorNode = xmldoc.SelectSingleNode("/ns:message/ns:error", nsMgr);    如果直接想定位到error,而不是从根开始,需要写为       xmldoc.SelectSingleNode("//ns:error", nsMgr); 

2.Dictionary

1.如果直接添加相同的键,会出错

Dictionary<String, Byte> dic = new Dictionary<String, Byte>();
            dic.Add("123", 1);
            MessageBox.Show(dic["123"].ToString());
            if (dic.ContainsKey("123"))
            {
                dic.Remove("123");
                dic.Add("123", 2);
            }
            MessageBox.Show(dic["123"].ToString());

排序:dic = dic.OrderBy(c => c.Key).ToDictionary(c => c.Key, c => c.Value);


3.获取某文件夹下所有txt文件

String path =@"X:\xxx\xxx";
 
//第一种方法
var files = Directory.GetFiles(path, "*.txt");
             
foreach(varfile in files)
    Console.WriteLine(file);
 
//第二种方法
DirectoryInfo folder =newDirectoryInfo(path);
            
foreach(FileInfo fileinfolder.GetFiles("*.txt"))
{
    Console.WriteLine(file.FullName);
}

4.目录不存在,则创建

if (Directory.Exists(spath)){}else{    DirectoryInfo directoryInfo = new DirectoryInfo(spath);    directoryInfo.Create();}

5.文件移动位置

string OrignFile,NewFile;    OrignFile = Server.MapPath(".")+"\\myText.txt";    NewFile = Server.MapPath(".")+"\\myTextCopy.txt";    File.Move(OrignFile,NewFile);


6.xml和对象互转

(1)对象--->xml文件

Department dep =new Department();

。。。。。。。往对象中写点数据

XmlSerializer serializer =new XmlSerializer(dep.GetType());
          TextWriter writer =new StreamWriter("Department.xml");
          serializer.Serialize(writer, oSer);
          writer.Close();

(2)xml文件--->对象

XmlSerializer serializer = new XmlSerializer(t);
            FileStream  stream = new FileStream (filePath,FileMode.Open );
            Department  dep=(Department)serializer.Deserialize(stream);
            stream.Close();  


7.winform判断网络连接状况

Ping p = new Ping();
             PingReply pr;
             pr = p.Send("119.75.218.45");//百度的IP
             if (pr.Status != IPStatus.Success)//如果连接不成功
             {
                 Console.WriteLine("未联网");
             }
             else
             {
                 Console.WriteLine("已联网");
             }
8.wince判断网络连接状况
try
            {
String address = "www.baidu.com";
int port = 80;
                IPHostEntry IpHost = Dns.GetHostEntry(address);

                Socket s = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
                IPEndPoint point = new IPEndPoint(IpHost.AddressList[0], port);
                s.Connect(point);


                if (s.Connected)
                {
                    Console.WriteLine("Connection established");
                    return true;
                }
                else
                {
                    Console.WriteLine("Connection failed");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }

9.字符串固定长度,多则补空格
str = str.PadRight(20, ' ');

0 0
原创粉丝点击