File文件创建路径,修改文本内容,截取文本内容

1.创建文件的路径最好不要写死,可以使用Server.MapPath:

Server.MapPath表示的路径,参考http://www.cnblogs.com/yangfan/archive/2008/05/23/1205976.html:

 ./当前目录
/网站主目录
../上层目录
~/网站虚拟目录

如果当前的网站目录为E:\wwwroot   应用程序虚拟目录为E:\wwwroot\company 浏览的页面路径为E:\wwwroot\company\news\show.asp
在show.asp页面中使用
Server.MapPath("./")   返回路径为:E:\wwwroot\company\news
Server.MapPath("/")    返回路径为:E:\wwwroot
Server.MapPath("../")   返回路径为:E:\wwwroot\company
Server.MapPath("~/")   返回路径为:E:\wwwroot\company
server.MapPath(request.ServerVariables("Path_Info")) 
Request.ServerVariables("Path_Translated")  
上面两种方式返回路径为 D:\wwwroot\company\news\show.asp


2.修改文本的内容

如将文本中的内容清空,参考:http://zhidao.baidu.com/link?url=EoJV6QG70RyITbAHpGIvvlEDHEg6ya_pAv5rV2hOCUldgNT7ezyLOzQFJtTm7A-7e_IGmnWTRdg8rInqVSTwt_:

FileStream fs = new FileStream("这里是你的txt路径",FileMode.Open,FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs,Encoding.Default);
string content = sr.ReadToEnd();//这个就是文本内容
content = content.Replace("你要删除的文本","");//这里的删除是把你不要的字符串替换成空串
StreamWriter sw = new StreamWriter(fs,Encoding.Default);
sw.Write(Content);
sw.Close();


3.截取文本内容:

A.

c#用正则表达式获取开始和结束字符串中间的值,参考http://www.shangxueba.com/jingyan/1830290.html

<span>	</span>/// <summary>
        /// 获得字符串中开始和结束字符串中间值
        /// </summary>
        /// <param name="str"></param>
        /// <param name="s">开始</param>
        /// <param name="e">结束</param>
        /// <returns></returns>
        public static string GetValue(string str, string s, string e)
        {
            Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            return rg.Match(str).Value;
        }

B.

C#中indexof和substring函数用法,参考:http://www.xuebuyuan.com/434429.html:

indexof() :在字符串中从前向后定位字符和字符串;所有的返回值都是指在字符串的绝对位置,如为空则为- 1

lastindexof() :在字符串中从后向前定位字符和字符串;、

用法和 indexof() 完全相同。

string test="asdfjsdfjgkfasdsfsgfhgjgfjgdddd";

test.indexof('d')      =2           //从前向后 定位 d 第一次出现的位置
test.indexof('d',1)    =2          //从前向后 定位 d 从第三个字符串 第一次出现的位置
test.indexof('d',5,2) =6     //从前向后 定位 d 从第5 位开始查,查2位,即 从第5位到第7位;


下面介绍 IndexOfAny ||lastindexofany

他们接受字符数组做为变元,其他方法同上,返回数组中任何一个字符最早出现的下标位置

如下

        char[] bbv={'s','c','b'};
        string abc = "acsdfgdfgchacscdsad";
        
        Response.Write(abc.IndexOfAny(bbv))=1
        Response.Write(abc.IndexOfAny(bbv, 5))=9
        Response.Write(abc.IndexOfAny(bbv, 5, 3))=9

lastindexofany 同上。
====================================================================
substring() 用法

string a="aadsfdjkfgklfdglfd"

a.substring(5)     //截取从第五位以后的所有字符串

a.substring(0,5)    //截取从第0位置开始长度为5的字符串





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值