asp net问题,在文件中搜索 [英] asp net problem, searching in a file

查看:74
本文介绍了asp net问题,在文件中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含ID和图像路径的文件,这些文件由|分隔.
1 |〜/images/img1.jpg
2 |〜/images/img2.jpg
--------------------
我想传递ID,因此它会搜索并返回图像的路径
我不想使用数据库,
它不返回路径,而仅返回null whuy?
我正在通过现有的ID


I have a file that contains ids and image path separated by |
1|~/images/img1.jpg
2|~/images/img2.jpg
--------------------
I want to pass the id, so it searches and returns the path of the image
i dont want to use database,,
it doesnt return the path ,, it only return null whuy ??
i am passing an exisiting id though


<pre lang="cs">public string GetImagePath(string id)
      {
          const string f2 = "C:\\idimg.txt";
          string myline;
          using (StreamReader r = new StreamReader(f2))
          {
              // 3
              // Use while != null pattern for loop


              while ((myline = r.ReadLine()) != null)
              {

                  string[] attr = myline.Split('|');
                  string myidimage = attr[0].ToString();
                  string pathimage = attr[1];
                  if (id == myidimage)
                  {
                      myline = pathimage;
                      return myline;
                  }
                  return null;

              }
          }

推荐答案

<pre lang="cs">public string GetImagePath(string id)
      {
          const string f2 = "C:\\idimg.txt";
          string myline;
          using (StreamReader r = new StreamReader(f2))
          {
              // 3
              // Use while != null pattern for loop


              while ((myline = r.ReadLine()) != null)
              {

                  string[] attr = myline.Split('|');
                  string myidimage = attr[0].ToString().Trim();
                  string pathimage = attr[1];
                  if (id == myidimage)
                  {
                      myline = pathimage;
                      return myline;
                  }
                  return null;

              }
          }



每当您从文本文件中读取字符串时,Trim()空格...



Trim() spaces whenever you read a string from textfile...


您的代码看起来不错,也许您的文件中有错误. 您使用字符串比较,因此请确保在"id"或"myidimage"的开头或结尾没有空格.
尝试使用:
id.Equals(myidimage, StringComparison.InvariantCultureIgnoreCase)
代替id == myidimage

同样,您也不需要attr [0]上的.ToString()-它已经是一个字符串.
Your code looks OK, maybe you have an error in the file.
You use string comparison, so make sure you do not have spaces at beginning or end of ''id'' or ''myidimage''.
Try using:
id.Equals(myidimage, StringComparison.InvariantCultureIgnoreCase)
instead of id == myidimage

also you don''t need .ToString() on attr[0] - it already is a string.


这篇关于asp net问题,在文件中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆