好的,所以我查看了与我的问题有关的所有其他问题,并且无法看到我出错的地方。我的目标是将骰子模拟器的结果写入文本文件,然后将该内容读入C#中的列表框。到目前为止,这是我的代码:
namespace WpfApplication1
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
Random RandomValue = new Random();
Random RandomValue2 = new Random();
using (StreamWriter outputFile = new StreamWriter("C:\\Example.txt"))
{
for (int i = 0; i < 100; i++)
{
int face1 = RandomValue.Next(1, 7);
int face2 = RandomValue2.Next(1, 7);
int toss = face1 + face2;
outputFile.WriteLine(toss);
}
outputFile.Close();
}
}
catch (Exception ex)
{
listBox1.Items.Add(ex);
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
try
{
using (StreamReader inputFile = new StreamReader("C:\\Example.txt"))
{
String toss;
for (int i = 0; i > 100; i++)
{
toss = inputFile.ReadLine();
listBox1.Items.Add(toss);
}
catch (Exception ex)
{
listBox1.Items.Add(ex);
}
}
}
}
}
当我尝试运行程序时,收到错误:System.UnauthorizedAccessException: Access to the path 'C:\Example.txt' is denied.
我认为我出错的地方实际上是在创建文本文件。当我尝试从中读取时,我收到相同的消息。我对C#非常陌生,并且觉得我没有正确地调用文件。任何见解都会非常受欢迎!
答案 0 :(得分:0)
大家好,首先我要感谢大家的帮助。我发现我哪里出错了,为什么它不能正常工作。首先,以管理员身份运行C#解决了访问问题,谢谢Selman22。之后,它正好写入文件,但不会读取文件并将数字移动到列表框中。在仔细检查代码之后,我意识到只要我大于100而不是更小,我就会声明for循环运行:
for (int i = 0; i > 100; i++)
将for语句更改为:
for (int i = 0; i < 100; i++)
它现在运行顺利。再次感谢大家!