【问题标题】:removing "~/" from the first of an sqldatareader object从 sqldatareader 对象的第一个中删除“~/”
【发布时间】:2014-09-26 18:42:58
【问题描述】:

我正在用FileUpload1.SaveAs(Server.MapPath(path) 保存图片的url,并初始化路径变量:

path = "~/Persian/slideshow/pictures/" + FileUpload1.FileName;

我必须添加“~/”,因为要插入解决方案并插入数据库,我需要这样做。我的问题是,当我想从数据库中读取此地图路径并创建图像标签时,我无法从对象中删除“~/”部分。这是我的代码:

dataReader = command.ExecuteReader();
imageList = "";
while (dataReader.Read())
{
    url = dataReader["PhotoUrl"].ToString();
    url = url.Substring(2, url.Length - 2);
    imageList += "{ image: '" + url + "', title: '" + dataReader["PhotoTitle"] + "', thumb: '" + dataReader["PhotoUrl"] + "', url: '" + dataReader["PhotoUrl"] + "' },";
}

这里的问题是我不能使用字符串相关的函数来更正路径。 我能做些什么 ?

非常感谢;)

【问题讨论】:

  • 你希望 url 在 JSON 中是什么样子的?
  • 子字符串有效。看起来在 ImageList 中您正在重用 dataReader["PhotoUrl"] 并且应该使用 url 变量。如果这不是问题,您能否显示 imageList 包含的内容以及您要查找的内容?
  • 不只是我想从使用 FileUpload1.SaveAs(Server.MapPath(path)) 添加到 url 的第一个 url 中删除 ~/。问题是当我从数据库中读取这个字段时,它不是一个字符串。所以我不能这样做
  • 用于在图库页面中加载图片的脚本。它是一个受保护的字符串,我从上面的代码中得到的错误是:“startIndex 不能大于字符串的长度。\r\n参数名称:startIndex”
  • 试试 dataReader["PhotoUrl"].ToString()

标签: asp.net database url sqldatareader


【解决方案1】:

所以上面的代码是完全正确的并且可以工作。我的问题是我从 url 的开头删除了 /。

path = "~/Persian/slideshow/pictures/" + FileUpload1.FileName;
dataReader = command.ExecuteReader();
            imageList = "";
            while (dataReader.Read())
            {
                url = dataReader["PhotoUrl"].ToString();
                url = url.Substring(1);
                imageList += "{ image: '" + url + "', title: '" + dataReader["PhotoTitle"] + "', thumb: '" + dataReader["PhotoUrl"] + "', url: '" + dataReader["PhotoUrl"] + "' },";
            }

【讨论】:

    【解决方案2】:

    如果您在数据库中保存路径为“~/Persian/slideshow/pictures/aa.gif”并且您希望在代码中包含“/Persian/slideshow/pictures/aa.gif”,您可以使用 .ToString () 和子字符串来实现这一点。

      string dbpath = "~/Persian/slideshow/pictures/aa.gif" ; // actual dbpath will be DataReaderObj["path"].ToString();
      string newpath = dbpath.Substring(1, dbpath.Length - 1); // this will remove ~ only
      string newpath = dbpath.Substring(2, dbpath.Length - 2); // to remove ~/
    

    在 while 循环中使用上述行,以获取所需的文件路径。

    【讨论】:

    • 是的!这就是答案;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2014-05-04
    • 2018-07-08
    相关资源
    最近更新 更多