不能使用streamwriter将随机数写入txt文件 [英] Cant write random number to txt file using streamwriter

查看:84
本文介绍了不能使用streamwriter将随机数写入txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建随机的6位数字并使用streamwriter将它们写在文本文件中,但它不起作用。我做错了什么?任何人都可以帮忙吗?



I'm trying create random 6 digit numbers and write them in a text file using streamwriter , but it doesnt work.Where am i doing wrong ? can anyone help ?

StreamWriter sw = new StreamWriter(@"C:\test.txt");
Random rd = new Random();
private void button1_Click(object sender, EventArgs e)
{
    String n = rd.Next(10000, 1000000).ToString("D6");
    sw.Write(n);
}





我的尝试:



streamwriter



What I have tried:

streamwriter

推荐答案

默认情况下, StreamWriter 类使用1024个字符的内部缓冲区。它只在缓冲区已满或者调用 Flush 关闭时写入文件。



您的程序从不调用 Flush 关闭方法,所以当程序退出时,缓存的内容将被丢弃。



每次写入后刷新写入器,数据将出现在文件中:

By default, the StreamWriter class uses an internal buffer of 1024 characters. It only writes to the file when the buffer is full, or when you call either Flush or Close.

Your program never calls the Flush or Close methods, so the buffered content is discarded when your program exits.

Flush the writer after each write, and the data will appear in the file:
private void button1_Click(object sender, EventArgs e)
{
    String n = rd.Next(10000, 1000000).ToString("D6");
    sw.Write(n);
    sw.Flush();
}


为什么这可能不起作用有很多原因,但最有可能是你的app不允许写入根目录 - 这是完全正常的,现代版本的Windows严格限制对root的写入权限,甚至更严格地限制写入启动驱动器的根目录以防止病毒感染。



尝试将文件移动到具有更自由访问权限的地方。

这可能会有所帮助:我应该在哪里存储我的数据? [ ^ ]



BTW:当你报告问题时,它不会工作不是很有帮助。始终尝试提供任何错误消息,以及您可以看到的任何可能相关的信息!
There are a number of reasons why this might not work, but the most likely is that you app isn't allowed to write to the root directory - this is perfectly normal, modern versions of Windows heavily restrict write permissions to root, and even more heavily restrict writes to the root of the boot drive to prevent virus infections.

Try moving the file to somewhere with more "liberal" access permissions.
This may help: Where should I store my data?[^]

BTW: when you report a problem, "it doesnt work" isn't very helpful. Always try to give any error messages, and anything you can see that could be relevant!


这篇关于不能使用streamwriter将随机数写入txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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