c#--常用方法(文件操作、外部接口请求、json与对象的相互转换、Dictionary字典常用功能等)

1.1、文件及目录的创建、删除、copy、移动等操作

//文件目录
DirectoryInfo TheFolder = new DirectoryInfo("c:\\Test");

//判断目录是否存在
if(!TheFolder.Exists)
{
    //创建目录
    directoryInfo.Create();
}

//遍历当前文件夹中的子目录
foreach(DirectoryInfo tf in TheFolder.GetDirectories())
{
    DirectoryInfo tf1=tf:
    //删除此目录(目录中为空)
    tf1.Delete();
    //删除此目录(包含此目录中的子目录和文件)
    tf1.Delete(true);
}


//遍历当前文件夹中的子文件
foreach(FileInfo tf in TheFolder.GetFiles())
{
    FileInfo fi1=tf;
    //获取文件后缀
    string extension = fi1.Extension;
    //获取文件完整路径
    string FilePath = fi1.FullName;
    //获取文件名称
    string FileName = fi1.Name;
    //获取父目录实例
    DirectoryInfo fi1 = tf.Directory;
    //获取目录完整路径
    string DirectoryName = tf.DirectoryName;
    //将文件转移到新位置
    File.Move("c:\\AAA\\源文件.txt","c:\\AAA\\目标文件.txt");
    //删除指定文件
    File.Delete("c:\\AAA\\源文件.txt");
}

//文件操作
FileInfo fi = new FileInfo("aaa.txt");
//判断文件是否存在
if(!fi.Exists)
{
    //创建文件
    fi.Create();
}
//将文件复制到新地址(不允许覆盖文件)
fi.CopyTo("c:\\Test\\新文件.txt");
//将文件复制到新地址(不如文件已存在则覆盖文件)
fi.CopyTo("c:\\Test\\新文件.txt", true);
//永久删除文件
fi.Delete();

1.2、文件流的读取

//实例文件操作类
StreamReader sw = new StreamReader(filePath);
while (bl_EndOfStream == false)
{
    //逐行读取文件
    string strLine = sw.ReadLine();
    //判断当前流的位置是否在流末尾(即最后一行)
    if (sw.EndOfStream)
    {
        //关闭流,并释放资源
        sw.Close();
        return;
    }
}

1.3、文件写入

//创建文件操作类对象(覆盖式写入文件)(1、FileMode.Create:如果文件存在则进行文件覆盖,如果不存在则进行CreateNew创建操作,如果文件存在但是被隐藏则引发异常,2、FileMode.OpenOrCreate:打开文件或者创建文件)(FileAccess.Write:文件的写访问权限)
using (FileStream fs1 = new FileStream("c:\\Test.txt", FileMode.Create, FileAccess.Write))
{
    using (StreamWriter sw = new StreamWriter(fs1))
    {
        //开始写入值  
        sw.WriteLine("测试");
        sw.Close();
        fs1.Close();
    }
}

2.后台调用接口

//2.1 WebRequest方式
//(1)post方式
private void button1_Click(object sender, EventArgs e)
{
     string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
}

public static string HttpPost(string url, string body)
{
     //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
     Encoding encoding = Encoding.UTF8;
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
     request.Method = "POST";
     request.Accept = "text/html, application/xhtml+xml, */*";
     request.ContentType = "application/json";
       
     byte[] buffer = encoding.GetBytes(body);
     request.ContentLength = buffer.Length;
     request.GetRequestStream().Write(buffer, 0, buffer.Length);
     HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
     {
          return reader.ReadToEnd();
     }
}

//(2)get方式
private void button1_Click(object sender, EventArgs e)
{
            string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京");
}

public static string HttpGet(string url)
{
        //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        Encoding encoding = Encoding.UTF8;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Accept = "text/html, application/xhtml+xml, */*";
        request.ContentType = "application/json";
           
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
        return reader.ReadToEnd();
    }
}
//2.2 HttpClient方式
//(1)Post方式
private async void button2_Click(object sender, EventArgs e)
{
     HttpClient client = new HttpClient();
     //由HttpClient发出Delete Method
     HttpResponseMessage response = await client.DeleteAsync("http://localhost:41558/api/Demo"+"/1");
     if (response.IsSuccessStatusCode)
         MessageBox.Show("成功");
}

private async void button3_Click(object sender, EventArgs e)
{
     //创建一个处理序列化的DataContractJsonSerializer
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
     MemoryStream ms = new MemoryStream();
     //将资料写入MemoryStream
     serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" });
     //一定要在这设定Position
     ms.Position = 0;
     HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
     content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
     HttpClient client = new HttpClient();
     //由HttpClient发出Put Method
     HttpResponseMessage response = await client.PutAsync("http://localhost:41558/api/Demo"+ "/1", content);
     if (response.IsSuccessStatusCode)
         MessageBox.Show("成功");
}
//(2)Get方式
using (WebClient client = new WebClient())
{
     client.Headers["Type"] = "GET";
     client.Headers["Accept"] = "application/json";
     client.Encoding = Encoding.UTF8;
     client.DownloadStringCompleted += (senderobj, es) =>
     {
         var obj = es.Result;
     };
     client.DownloadStringAsync("http://localhost:41558/api/Demo");
}

3.c#进行json与对象的转换

//3.1 对象转换为json字符串

//reponse:将要转换为json字符串的对象实体
var reponseEntity = JsonConvert.SerializeObject(reponse);

//3.2 json转换为已知对象

//定义类,与json格式保持一致
public cless Responseentity
{
    public string name{get;set;};
    public string sex{get;set;};
}
public class TestClass
{
    public void TestFunction()
    {
        //转换1
        Responseentity resp = new Responseentity();
        // Responseentity.GetType():获取目标对象的类型   
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(Responseentity.GetType());
        MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes("将要被转换的json字符串"));
        Responseentity = (ResponseData[])serializer.ReadObject(mStream);

        //转换2
        StringBuilder JsonVisitRecordList = new StringBuilder();

        //获取List<VisitRecord>对象
        List<VisitRecord> VisitRecordList = visitRecordModel.VisitRecordList(userId,startDate,enddate, pageindex, pagesize);

        JavaScriptSerializer json = new JavaScriptSerializer();

        //将对象(List<VisitRecord>)转换为json字符串(JsonVisitRecordList)
        json.Serialize(VisitRecordList, JsonVisitRecordList);
        Console.WriteLine(JsonVisitRecordList);

        //将json字符串(JsonVisitRecordList)转换为List<VisitRecord>对象()
        List<VisitRecord> JsonToVisitRecordList json.Deserialize<List<VisitRecord>>(JsonVisitRecordList.ToString());
    }
}

4.Dictionary字典

 

//实例一个Dictionary
Dictionary<object, object> ownerID_dic = new Dictionary<object, object>();

//给Dictionary赋值(注:Key值不能重复)
ownerID_dic.add("Key1","Value");
ownerID_dic.add("Key2","Value");
ownerID_dic.add("Key3","Value");

//获取当前字典中键/值的数量
int count = ownerID_dic.Count;

//判断字典中的key值是否包含当前值
ownerID_dic.ContainsKey("aa");

//判断字典中的value值是否包含当前值
ownerID_dic.ContainsValue("aa");

//将字典中的key是当前值的数据删除
ownerID_dic.Remove("");

//获取当前字典中键为当前值的value信息(注:如果当前键不存在则抛出异常)
var value = var a = ownerID_dic["aa"];

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值