步步为营-14-文件操作

1 对文件的操作-File类

  常用的操作:

  File.Exis();判断文件是否存在

  File.Create ();创建

  File.Move();剪切

  File.Copy();复制

  File.Delete();删除

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //判断文件是否存在
            if (File.Exists("1.txt"))
            {
                //删除文件
                File.Delete("1.txt");
                //创建文件
                File.Create("2.txt");
            }
            else {
                File.Create("1.txt");
            }
            //文件赋值
            File.Copy(@"C:\Users\home\Desktop\宽带连接.txt",@"E:\asd.txt");
            //文件剪切
            File.Move(@"E:\asd.txt",@"C:\Users\home\Desktop\宽带连接2.txt");

        }
    }
}
File

  读取文件

  string [] str = File.ReadAllLines(@"C:\Users\1.txt");

  string str2 = File.ReadAllText(@"C:\Users\1.txt");

    通过字节数组转化成字符串

  byte [] buffer = File.ReadAllBytes(@"C:\Users\1.txt");

  string str = Encoding.UTF8.GetSstring(buffer);

  cw(str);

  写文件

  第一种方法

    string abc = "要写入的字符串";

    //1先将字符串转换为字节数组

    byte[] buffer = Encoding.Default.GetBytes(abc);

    File.WriteAllBytes(@"C:\Users\1.txt",buffer);

  第二种

  File.WriteAllLines(@"C:\Users\1.txt",new string[]{"a","b"});

  第三种

  File.WriteAllText(@"C:\Users\1.txt",new string[]{"c"});

File比较简单,适合操作小的文本文件

ps:另一种通过js判断文件是否存在

  aherfStr= "/Download.aspx?Url=/FileTemplate/Attachments/15_4_3/"+codeName+ ".xlsx";   
 
        //进一步判断这个文件在服务器上是否存在
        
        if(FileExist(aherfStr)){
            $(".template").show();
        }else{
            $(".template").hide();
        } 


 function FileExist(FileURL)
    {        
        var xmlhttp;
        if (window.ActiveXObject)  
        {  
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
        }  
        else if (window.XMLHttpRequest)  
        {  
            xmlhttp = new XMLHttpRequest();  
        }          
        xmlhttp.open("get",FileURL,false);
        xmlhttp.send();
        if(xmlhttp.readyState==4)
        { 
            if(xmlhttp.status==200) return true ; 
            else if(xmlhttp.status==404) return  false;
            else return false; 
        }else{
            return  false;
        }
    }
View Code

 

posted @ 2017-04-16 11:35  逍遥小天狼  阅读(200)  评论(0编辑  收藏  举报