问题
Ok so I have looked at every other question that relates to my problem and can't see where I am going wrong. My objective is to write the results of a dice simulator to a text file then read that contents into a listbox in C#. Here is my code so far:
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);
}
}
}
}
}
When I try running the program I receive the error: System.UnauthorizedAccessException: Access to the path 'C:\Example.txt' is denied.
I think that where I am going wrong is actually creating the text file. When I try to read from it I receive the same message. I am extremely new to C# and have the feeling that I am not calling the file correctly. Any insight would be extremely welcome!
回答1:
Alright everyone, first I want to thank you all for your help. I found where I was going wrong and why it was not working correctly. First, running C# as an administrator solved the access issues, thank you Selman22. After that it was writing to the file just fine but would not read the file and move the digits to the listbox. After reviewing the code more closely I realized I was declaring the for loop to run as long as I was greater than 100 rather than smaller:
for (int i = 0; i > 100; i++)
After changing the for statement to:
for (int i = 0; i < 100; i++)
It now runs smoothly. Thank you all again!
来源:https://stackoverflow.com/questions/25962571/problems-reading-and-writing-to-a-text-file-in-c-sharp