一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net 如何从C# 字符串中读取字符

时间:2022-06-25 05:04:11 编辑:袖梨 来源:一聚教程网

asp教程.net 如何从c# 字符串中读取字符
定义字符串并将其转换为字符数组,然后,可以使用适当的 stringreader.read 方法按需要读取该字符数组。
[c#]

using system;
using system.io;
public class charsfromstr
{
  public static void main(string[] args)
  {
  // create a string to read characters from.
  string str = "some number of characters";
  // size the array to hold all the characters of the string,
  // so that they are all accessible.
  char[] b = new char[24];
  // create a stringreader and attach it to the string.
  stringreader sr = new stringreader(str);
  // read 13 characters from the array that holds the string, starting
  // from the first array member.
  sr.read(b, 0, 13);
  // display the output.
  console.writeline(b);
  // close the stringreader.
sr.close();
  }
}

示例允许您在现有字符串中从指定的位置开始读取一定数目的字符。使用 stringreader 完成此操作

asp.net教程 2.0中,使用了一种在运行时解析为连接字符串值的新的声明性表达式语法,按名称引用数据库教程连接字符串。连接字符串本身存储在 web.config 文件中的 <connectionstrings> 配置节下面,以便易于在单个位置为应用程序中的所有页进行维护。

  范例程序代码如下:

<?xml version="1.0"?>
<configuration>
<connectionstrings>
<add name="pubs" connectionstring="server=localhost;
integrated security=true;database=pubs;persist security info=true"
providername="system.data.sqlclient" />
<add name="northwind" connectionstring="server=localhost;
integrated security=true;database=northwind;persist security info=true"
providername="system.data.sqlclient" />
</connectionstrings>
<system.web>
<pages stylesheettheme="default"/>
</system.web>
</configuration>

  

程序代码说明:在上述范例的程序代码中,我们在web.config文件中的<connectionstrings> 配置节点下面设置了两个数据库连接字符串,分别指向pubs和northwind两个示例数据库。注意,在2.0中引进了数据源控件,例如sqldatasource 控件,我们可以将sqldatasource 控件的 connectionstring 属性被设置为表达式 <%$ connectionstrings:pubs %>,该表达式在运行时由 asp.net 分析器解析为连接字符串。还可以为sqldatasource 的 providername 属性指定一个表达式,例如 <%$ connectionstrings:pubs.providername %>。其具体的用法和新特征将在以后的章节进行详细的介绍。现在有个基础的了解即可。

  当然,我们也可以用下面的方式从配置文件直接读取数据库连接字符串。首先我们需要引用using system.web.configuration命名空间,该命名空间包含用于设置 asp.net 配置的类。

  string connectionstring =configurationmanager.connectionstrings["northwind"].connectionstring;

  程序代码说明:在上述范例的程序代码中,我们可以利用connectionstrings["northwind"]读取相应的northwind字符串。同理以可以利用connectionstrings["pubs"]读取相应的pubs字符串

热门栏目