生成文本文件代码
问题描述:
请参阅我的代码.在这里,我从数据库中读取数据并写入文本文件.但是在这里,我在做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 thedo whileloop. 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";