Null Refrence Exception Unhandled in my Microprocessor simulator [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
So I have my memory class which looks like this:
namespace GeminiCore
{
public class Memory
{
public static int[] memory = new int[256];
public string nextInstruction;
public static int cacheSize = 8;
public CPU myCPU;
public struct frame
{
public bool dirtyBit;
public int isEmpty;
public int value;
public int tag;
public frame(int cacheSize)
{
dirtyBit = false;
isEmpty = 1;
value = 0;
tag = 0;
}
}
public int solveMemory(int value, int instr, frame[] myCache)
{
Console.WriteLine("I reached the solveMemory!!!");
int block = value % cacheSize;
if(instr == 127 || instr == 125 || instr == 124 || instr == 123
|| instr == 122 || instr == 121|| instr == 120)
{
Console.WriteLine("I reached the read section!!!");
if(myCache[block].isEmpty == 0) //Read hit
if(myCache[block].tag == value)
return myCache[block].value;
else
{
myCache[block].value = memory[value]; //Read Miss
myCache[block].tag = value;
myCache[block].isEmpty = 0;
Console.WriteLine("Read Miss --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
return myCache[block].value;
}
}
else
{
Console.WriteLine("I reached the write section!!!");
if (myCache[block].isEmpty == 1) //Write Miss
{
Console.WriteLine("Write Miss --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
memory[value] = myCPU.ACC;
}
else
{
if (myCache[block].dirtyBit == false)
{
if (myCache[block].tag != value)
{
myCache[block].value = myCPU.ACC; //Write Hit
myCache[block].dirtyBit = true;
myCache[block].tag = value;
Console.WriteLine("Write Hit --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
}
}
else
{
memory[myCache[block].tag] = myCache[block].value;
myCache[block].value = myCPU.ACC;
myCache[block].tag = value;
myCache[block].dirtyBit = false;
Console.WriteLine("Write Hit --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
}
}
}
return value;
}
}
}
and then I have my CPU class, and I will just post a small snippet of where the error is occurring:
public Memory myMemory;
public static Memory.frame[] myCache = new Memory.frame[Memory.cacheSize];
public void doInstruction()
{
var instr = (finalCodes[i] >> 9) & 127; //Parses op code to find instruction
var immed = (finalCodes[i] >> 8) & 1; //Parses op code to find immediate value
var value = (finalCodes[i] & 255); //Parse op code to find value
foreach (Memory.frame x in myCache)
{
Console.WriteLine("Dirtybit: " + x.dirtyBit + " isEmpty: " + x.isEmpty + " tag: " + x.tag + " value: " + x.value);
}
switch (instr)
{
case (127): //LDA instruction
if (immed == 1)
ACC = value;
else if (immed == 0)
//ACC = Memory.memory[value];
ACC = myMemory.solveMemory(value, instr, myCache);
break;
case (126): //STA instruction
if (immed == 0)
{
Console.WriteLine("The value is: " + value + " The instruction is: " + instr);
foreach (Memory.frame x in myCache)
{
Console.WriteLine("Dirtybit: " + x.dirtyBit + " isEmpty: " + x.isEmpty + " tag: " + x.tag + " value: " + x.value);
}
//Memory.memory[value] = ACC;
myMemory.solveMemory(value, instr, myCache);
}
So here is my problem, when I run my test which takes in assembly code and translates it to binary then runs through the code, when I get to the second command "sta" it should go to the line:
myMemory.solveMemory(value, instr, myCache);
It then gives me a Null Reference Exception when it reaches that point. As you can see I have some command line output to try and see where it is going. It prints out the contents of myCache right before that line. It does not reach any of the debug statements in the solveMemory function however, not even the first one that says:
Console.WriteLine("I reached the solveMemory!!!");
I'm not really sure what is causing this error and I've been looking at it for quite some time. Hopefully one of you will be able to find where exactly I am messing up. Thanks for the time.

public Memory myMemory;
should be:
public Memory myMemory = new Memory();

Related

I'm curious about the logic that checks only once at a certain time

I would like help.
There are some problems with the code.
I want to do only one inspection at a certain time every day.
In particular, the problem is the most serious in DateTime.Now.Hour == 11 part.
I am having difficulty checking certain times. I need to write code that can be checked only once at 11:00 in the whlie statement.
I created a license file and checked the date of the file.
public static CResult Dailytime(string date)
{
CResult result = new CResult();
if(result.nRet == 0)
{
while (true)
{
if (result.nRet == 1 || result.nRet == 2)
{
return result;
}
if (DateTime.Now.Hour == 11)
{
result = DailyCheckData(date);
if(result.nRet == 1 || result.nRet == 2)
{
return result;
}
}
System.Threading.Thread.Sleep(60 * 30 * 1000);
}
}
return result;
}
public static CResult DailyCheckData(string data)
{
CResult result = new CResult();
DateTime licenseDate = Convert.ToDateTime(data);
string dateNow = DateTime.Now.ToString("yyyy-MM-dd");
int compareDate = DateTime.Compare(Convert.ToDateTime(data), DateTime.Now);
if (licenseDate.ToString("yyyy-MM-dd") == dateNow)
{
result = ExpirationCertificate();
Console.WriteLine("Result = " + result.Result + " Msg = " + result.Msg + " nRet = " + result.nRet);
return result;
}
else
{
if (compareDate > 0)
{
result = TrueCertificate();
Console.WriteLine("Result = " + result.Result + " Msg = " + result.Msg + " nRet = " + result.nRet);
}
else if (compareDate <= 0)
{
result = ExpirationCertificate();
Console.WriteLine("Result = " + result.Result + " Msg = " + result.Msg + " nRet = " + result.nRet);
}
return result;
}
}
CResult class
nRet= 0 or 1 or 2
0 = fasle date
1 = false file
2 = true
Suggest or suggest ways to improve.
Can you try create a variable for DateTime.Now, after a line of code that value change.
DateTime licenseDate = Convert.ToDateTime(data);
string dateNow = DateTime.Now.ToString("yyyy-MM-dd");
int compareDate = DateTime.Compare(Convert.ToDateTime(data), DateTime.Now);
To
DateTime licenseDate = Convert.ToDateTime(data);
var now = DateTime.Now;
string dateNow = now.ToString("yyyy-MM-dd");
int compareDate = DateTime.Compare(licenseDate, now);
you shouldn't use Thread.Sleep() method for such a long duration. It is poor programming logic to make the thread sleep for such a long period.
What you can do to solve this is, is to make a Timer. There's an example attached in the link. A simple snippet to match your logic would be:
licenseStart = //setYours
lastCheck = DateTime.Now;
nextCheck = now.AddDays(1); // now.AddHours(1)
var timer = new Timer(o=>{/* Do work*/}, null, TimeSpan.Zero, nextCheck);
Hope it helps!
I asked about logic that can only loop once at 11 o'clock.
But I could not find the right answer and I found the answer.
I do not speak English well.
That's why others do not understand the intent of the question.
bool bOnce = true;
//bool s0nce = true;
while (true)
{
if (DateTime.Now.Hour == 11 && bOnce)
{
//run code
}
if (bOnce == true)
bOnce = false;
else
bOnce = true;
Thread.Sleep(10 * 60 * 1000);
}

Discord.NET Users playing the same game

I am trying to create a command that returns the number of guild members that are currently playing a specified game.
Example (! is my prefix): !playing League of Legends.
If there are 5 members playing League of Legends, output:
There are 5 users currently playing League of Legends.
I set up the following, from debugging I was able to pick up that v.Game.toString() returns the correct string but for some reason the if statement does not trigger. It also catches an exception that is thrown whenever members are not playing a game (I assumed it's null?), is there a workaround for that? Why does this not count how many members are playing a certain game?
[Command("playing")]
public async Task playingGame(params string[] s)
{
string gameName = "";
int count = 0;
for (int i = 0; i < s.Length; i++)
{
gameName += s[i] + " ";
}
await Context.Channel.SendMessageAsync("Looking for: " + gameName);
var u = Context.Guild.Users;
foreach (var v in u)
{
await Context.Channel.SendMessageAsync("v = " + v.ToString());
try
{
await Context.Channel.SendMessageAsync(v.Game.ToString());
if (v.Game.ToString().ToLower().Equals(gameName.ToLower()))
{
count++;
await Context.Channel.SendMessageAsync("Found match, count = " + count);
}
}
catch (Exception x)
{
await Context.Channel.SendMessageAsync("Exception throw caught");
}
}
if (count > 1) {
await Context.Channel.SendMessageAsync("There are " + count + " users currently playing " + gameName + ".");
}
else if (count == 1)
{
await Context.Channel.SendMessageAsync("There is " + count + " user currently playing " + gameName + ".");
}
else if (count == 0)
{
await Context.Channel.SendMessageAsync("No one is currently playing " + gameName + ".");
}
}
This is the exception:
System.ArgumentException: Argument cannot be blank
Parameter name: Content
at Discord.Preconditions.NotNullOrEmpty(String obj, String name, String msg)
at Discord.API.DiscordRestApiClient.<CreateMessageAsync>d__77.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
Pic of where if statement should trigger (username blocked for privacy reasons):
There is no need to have params string[] s for the game parameter. Just use the Remainder attribute.
I have also simplified this code alot :
[Command("playing")]
public async Task GetUsersPlaying([Remainder]string game)
{
await Context.Message.DeleteAsync();
var users = Context.Guild.Users.Where(x => x.Game.ToString() == game).Distinct().Select(x => x.Username);
var count = users.Count();
var SeparatedList = string.Join(", ", users);
string message;
if (count > 1)
message = $"There are {count} users playing {game}. [{SeparatedList}]";
else if (count == 1)
message = $"There is {count} user playing {game}. [{SeparatedList}]";
else
message = $"There is no one playing {game}.";
await Context.Channel.SendMessageAsync(message);
}

System.IO.File.WriteAllText outputs gibberish C#

I have a simple program in C# that is supposed to output a text file containing a sequence of character separated by commas. I also output the resulting sequence on the console and it looks fine, however, the text file is full of weird character and no commas.
This is the output :
㔳㌬ⰵⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰳⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰴⰰⰰⰰⰳⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰲⰱⰱⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰲⰰⰳⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰱⰱⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰳⰰⰴⰴⰴⰰⰰⰰⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰰⰰⰴⰴⰴⰰⰰⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰱⰱⰱⰱⰱⰲⰰⰲⰱⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰰⰰⰰⰰⰰⰵⰰⰵⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰲⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰵⰰⰵⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰲⰰⰰⰵⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰰⰱⰰⰰⰰⰰⰰⰰⰰⰰⰰⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰵⰰⰰⰰⰴⰴⰰⰰⰰⰰⰱⰱⰱⰱⰱⰱⰰⰰⰱⰱⰱⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰰⰰⰰⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰵⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰳⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰵⰰⰰⰰⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰰⰰⰰⰰⰰⰰⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴⰴ
This is what is supposed to be outputted
35,35,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,4,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,0,0,0,
0,0,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,4,4,4,4,4,0,0,4,4,4,4,4,4,4,4,4,0,0,0,4,4,4,4,
4,4,4,4,0,0,0,0,0,0,0,0,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,0,
0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
As I said, what is supposed to be outputted is the string that is directly passed into File.WriteAllText.
Am I missing something ? I don't understand what i'm doing wrong. It seems to be working sometimes, but with other string it does not. I can find no relation between the sequences that works and those that do not.
Here is the whole code, it's a simple program that read a bitmap and output the sequence depending on the pixel. It's badly & quickly written but it's supposed to work, i see no reason it shouldn't.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(args[0]);
Bitmap Map = new Bitmap(args[0]);
var MapRGB = Map.Clone(new Rectangle(0, 0, Map.Width, Map.Height), PixelFormat.Format32bppRgb);
int height = Map.Height;
int widht = Map.Width;
string MapText = height.ToString() + "," + widht.ToString() + ",";
for (int h = 0; h < height; h++)
{
for (int w = 0; w < widht; w++)
{
Color currentPixel =
MapRGB.GetPixel(w ,h );
if (currentPixel.ToArgb() == Color.White.ToArgb())
{
MapText = MapText + "0,";
}
if (currentPixel.ToArgb() == Color.Black.ToArgb())
{
MapText = MapText + "1,";
}
if (currentPixel.ToArgb() == Color.Gray.ToArgb())
{
MapText = MapText + "2,";
}
if (currentPixel.ToArgb() == Color.Yellow.ToArgb())
{
MapText = MapText + "3,";
}
if (currentPixel.ToArgb() == Color.Green.ToArgb())
{
MapText = MapText + "4,";
}
if (currentPixel.ToArgb() == Color.Red.ToArgb())
{
MapText = MapText + "5,";
}
Console.Clear();
Console.WriteLine(args[0] + " WROKING " + w.ToString() + " OF " + widht.ToString() + " IN " + h.ToString() + " OF " + height.ToString());
}
}
Console.Clear();
Console.Write(MapText);
System.IO.File.WriteAllText(Environment.CurrentDirectory + "/Map.bwn", MapText);
Console.ReadKey();
}
}
Not absolutely sure but could be an encoding issue. Use the other overload File.WriteAllText(String, String, Encoding) which takes a encoding type as argument like
File.WriteAllText(filePath, stringMessage, Encoding.UTF8);

KeyNotFoundException was unhandled, putting the key in the library

I am making a program that puts different participants in a library with a particular key. I came to the problem where I got a KeyNotFoundException.
Here you can see my code error which was at if (sessionPersonsSchedule[s].Count == s.MaxParticipants)
public bool personAddToLibrary(int personsIn)
{
if (personsIn == participants.Count)
{
return true;
}
else
{
for ( int j = 0; j < participants[personsIn].Preferences.Count; j++ )
{
Participant p = participants[personsIn];
Session s = sessions[p.Preferences[j] - 1];
SessionPersonsSchedule[s]
if (testSessions(s))
{
sessionPersonsSchedule[s].Add(p);
Console.Write(personsIn + ". " + p + "is added to session " + s);
personAddToLibrary(personsIn + 1);
if (personsIn == participants.Count)
{
return true;
}
}
else
{
sessionPersonsSchedule[s].Remove(p);
Console.Write(personsIn + ". " + p + "is deleted from session " + s);
}
}
}
return false;
}
public bool testSessions(Session s)
{
if (sessionPersonsSchedule[s].Count == s.MaxParticipants)
{
return false;
}
else
{
return true;
}
}
The KeyNotFoundException indicates that you are trying to index into the collection with a key that doesn't exist in the collection.
So, before you do sessionPersonsSchedule[s] in testSessions, you can make sure that s exists first by calling Dictionary.ContainsKey.

Loading multiple files Exception error C#

I am making the game minesweeper and I am trying to implement a highScores feature. I am trying to load 3 different files (each one holds the high scores for each of the 3 difficulty settings) into 3 different richTextBox's. When I run the app and click the 'high scores' tab from the menu strip it works the first time. However if I play a game and then try to access the high scores form I get an Exception error -
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
'C:\Users\jzcon_000\Copy\Visual
Studio\Projects\Assignment1\Assignment1\bin\Debug\highScoresMed.txt'
because it is being used by another process
This is where the call is made
private void highScoresToolStripMenuItem_Click(object sender, EventArgs e)
{
Minesweeper.HighSc highScore = new Minesweeper.HighSc();
highScore.read();
highScore.Show();
}
This is the method in my HighSc class
public void read()
{
StreamReader readerE = File.OpenText("highScoresEasy.txt");
StreamReader readerM = File.OpenText("highScoresMed.txt");
StreamReader readerH = File.OpenText("highScoresHard.txt");
if (readerE != null)
{
string readEasy = File.ReadAllText("highScoresEasy.txt");
richTextBox1.Text = readEasy;
}
readerE.Close();
if (readerM != null)
{
string readMed = File.ReadAllText("highScoresMed.txt");
richTextBox2.Text = readMed;
}
readerM.Close();
if (readerH != null)
{
string readHard = File.ReadAllText("highScoresHard.txt");
richTextBox3.Text = readHard;
}
readerH.Close();
}
Heres the save high scores class
namespace Minesweeper
{
class Save
{
int diff, hr, min, sec;
string player;
public Save(int difficulty, int hour, int minute, int second, string playerN)
{
diff = difficulty;
hr = hour;
min = minute;
sec = second;
player = playerN;
}
public void save()
{
StreamWriter writerEasy = new StreamWriter("highScoresEasy.txt", true);
StreamWriter writerMed = new StreamWriter("highScoresMed.txt", true);
StreamWriter writerHard = new StreamWriter("highScoresHard.txt", true);
if (diff == 1)
{
writerEasy.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerEasy.Close();
}
else if (diff == 2)
{
writerMed.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerMed.Close();
}
else if (diff == 3)
{
writerHard.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerHard.Close();
}
}
}
}
So when you have the difficulty level set to 1 and then save, you open the StreamWriters for both the level2 and level3 but never close them.
This could only mean that when you try to load the highscore for these two levels you will find your files locked by your previous save.
You should change your Save method to open only the required file
public void save()
{
if (diff == 1)
{
using(StreamWriter writerEasy = new StreamWriter("highScoresEasy.txt", true))
{
writerEasy.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
}
}
else if (diff == 2)
....
else if (diff == 3)
....
I suggest also to use the using statement in your reading method to be sure that also in case of exceptions the stream are correctly disposed

Categories