生成文本文件代码 [英] Generate text file code

查看:75
本文介绍了生成文本文件代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅我的代码.在这里,我从数据库中读取数据并写入文本文件.但是在这里,我在做while循环时有些错误.它会在12倍内生成1st数据,而其他数据是1倍,并且因为缺少超链接,因此也是如此.请任何人帮我.

please see my code. Here i read data from database and write into text file. But here i some mistake in do while loop. It generate 1st data in 12 times and others are 1 times and the hyperlink is also missing because. please any one help me.

SqlConnection con = Database.GetConnection();
        string str = "SELECT top 12 id,title FROM listTable where status=1 and admin_no is NULL order by sticky desc,date desc";
        SqlCommand com = new SqlCommand(str, con);
        SqlDataAdapter sqlDa = new SqlDataAdapter(com);
        sqlDa.Fill(dt);
        int count=0;
     
        SqlDataReader dr = com.ExecuteReader();
       while (dr.Read())
        {
            do
            {
                html = html + "<li><a href=" + "/news/" + dr["title"] + "-" + dr["id"] + ".aspx" + ">" + dr["title"] + "</a></li>"+"<br/>";
                count = count + 1;
            } while (count < 12);
        }
        string path = @"C:\news\gen.txt";
       
        if (!File.Exists(path))
        {
            
        }
        
            string appendText = html + Environment.NewLine;
            File.AppendAllText(path, appendText);
            lbltxt.Text = "File Created Successfully";



在此先感谢



Thanks in advance

推荐答案

假定您要输出的前十二个值如下:
Assuming that you are trying to output up to the first twelve values:
while (dr.Read() && count < 12)
  {
  html = html + "<li>" + dr["title"] + "</li>"+"<br />";
  count = count + 1;
  }

但是您不应该那样做:改为使用StringBuilder:

But you shouldn''t do it that way: use a StringBuilder instead:

StringBuilder sb = new StringBuilder();
while (dr.Read() && count < 12)
  {
  sb.Append(string.Format("<li><a href="/news/{0}-{1}.aspx">{2}</a></li><br />",
                          dr["title"], dr["id"], dr["title"]));
  count++;
  }
html += sb.ToString();


尝试使用命名空间系统的解决方案使用stringbuilder.Text"
Try using stringbuilder for this solution using a namespace system.Text"


删除do while循环.您正在获取12仅记录.

Remove the do while loop. You are fetching 12 records only.

while (dr.Read())
       {

               html = html + "<ul><li>" + dr["title"] + "</li></ul>"+"<br />";

       }



此外,如果要查看超链接,则需要将文件另存为htm而不是txt



Moreover, if you want to see the hyperlink, you need to save file as htm not txt

string path = @"C:\news\gen.htm";


这篇关于生成文本文件代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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