欢迎使用CSDN-markdown编辑器

来源:互联网 发布:linux中cat命令语法 编辑:程序博客网 时间:2024/04/28 04:35

C#读取txt文本

1丶绝对路径下获取txt文本

public static void GetTxt(string path)        {            if (string.IsNullOrEmpty(path))            {                MessageBox.Show("文件位置必须填写");                return;            }            //创建读取流            StreamReader sr = new StreamReader(path);            try            {                txtContent = sr.ReadToEnd();            }            catch (IOException ex)            {                MessageBox.Show(ex.Message);            }            sr.Close();        }

2、虚拟路径下获取文本

public static void SendUrl(string path)        {            string StrReturn = "";            WebResponse result = null;            try            {                WebRequest req = WebRequest.Create(path);                result = req.GetResponse();                Stream ReceiveStream = result.GetResponseStream();                Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");                StreamReader sr = new StreamReader(ReceiveStream, encode);                Char[] read = new Char[256];                int count = sr.Read(read, 0, 256);                while (count > 0)                {                    String str = new String(read, 0, count);                    StrReturn += str;                    count = sr.Read(read, 0, 256);                }            }            catch (Exception e)            {                StrReturn += e.ToString();                StrReturn += "找不到请求 URI,或者它的格式不正确";            }            finally            {                if (result != null)                {                    result.Close();                }            }            txtContent=StrReturn.Trim();        }
0 0
原创粉丝点击