System.IO.File.WriteAllText outputs gibberish C# - 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,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,0,0,0,0,0,0,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,4,4,4,0,0,0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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);
Related
Compare a string in if()
I'm trying to compare a string in an if(string = ""), but it's apparently not the same the string is "thisColor", it is defined by the content of a file. I tried using Debug.Log(thisColor), the result is "rouge" but it's not recognized in if(thisColor == "rouge"). I also tried switch(thisColor) then case()... Maybe it's the encoding..? Here is the code snippet: thisColor = ""; pixelSetup = GameObject.Find("Pixel" + setupPixelNumber.ToString()); setupPixelNumber += 1; if (File.Exists("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt")) { thisColor = File.ReadAllText("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt"); } else { File.Create("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt").Dispose(); } string[] retourSuppr = new string[] { "\n" }; foreach(var c in retourSuppr) { thisColor = thisColor.Replace(c, string.Empty); } pixell = pixelSetup; pixell.GetComponent<Renderer>().enabled = true; Debug.Log("thisColor = |" + thisColor + "|"); if (thisColor != "") { Debug.Log(thisColor); if (thisColor == "rouge") { Debug.Log("done."); pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 0, 0, 1); thisColor = ""; } else if (thisColor == "orangeF") { pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 70f / 255f, 0 / 255f, 1); thisColor = ""; } else if (thisColor == "orange") { pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 128f / 255f, 0 / 255f, 1); thisColor = ""; } else { Debug.Log("Passed"); } thanks :)
This is because your file is encoded with something different than UTF-8, which is the default reading method used by ReadAllText As said in this answer you can tell ReadAllText to use unicode instead. File.ReadAllText("yourTextFile.txt", Encoding.Unicode);
i am not sure you "thisColor = File.ReadAllText("C:/PekmiIndustries/MVPlace/Pixel" + pixell + ".txt");" result,but i think the result contains space bar,so you can try this: thisColor=thisColor.Replace(" ","")
If you are sure that "rouge" is among the words, just use Contains: if (thisColor.Contains("rouge")) { // do something }
DeviceCapabilities generates error: data is invalid
I want to get a printer's list of paper source, paper size, etc. I slightly modified the codes from http://www.pinvoke.net/default.aspx/Enums/DeviceCapabilities.html?diff=y The codes sometimes work, sometimes not. The proplem is DeviceCapabilities(DeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, (IntPtr)null, (IntPtr)null) returns -1. the last error is "data is invalid" Restart computer may not solve the problem. Once getting the problem, next time maybe OK maybe not. So what is the problem here? ArrayList arrBinName; string sError = ""; GetBins("\\Lindy-PC.MyCpmpany.local\HP LaserJet 4000 Series PCL 5", "LPT1", out arrBinName, out sError); public static bool GetBins(string DeviceName, string strPort, out ArrayList BinName, out string strError) { strError = ""; BinName = new ArrayList(); IntPtr pAddr = default(IntPtr); int offset = 0; int nRes = DeviceCapabilities(DeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, (IntPtr)null, (IntPtr)null); //Returns -1 if (nRes >= 0) { try { pAddr = Marshal.AllocHGlobal((int)nRes * 24); nRes = DeviceCapabilities(DeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, pAddr, (IntPtr)null); if (nRes < 0) { strError = new Win32Exception(Marshal.GetLastWin32Error()).Message + "[" + DeviceName + ": " + strPort + ".DC_BINNAMES]"; return false; } offset = pAddr.ToInt32(); for (int i = 0; i < nRes; i++) { BinName.Add(Marshal.PtrToStringAnsi(new IntPtr(offset + i * 24))); } } finally { Marshal.FreeHGlobal(pAddr); } } else strError = new Win32Exception(Marshal.GetLastWin32Error()).Message + "[" + DeviceName + ": " + strPort + ".DC_BINNAMES]"; return true; }
As aggaton mentioned in his or her comment, DeviceCapabilities requires two calls in certain circumstances and retrieving bin names is one of them. You should first read the documentation for DeviceCapabilities. Then go back and look at the sample code you used. You omitted a key step: // BinNames nRes = DeviceCapabilities(strDeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, (IntPtr)null, (IntPtr)null); pAddr = Marshal.AllocHGlobal((int)nRes * 24); nRes = DeviceCapabilities(strDeviceName, strPort, DeviceCapabilitiesFlags.DC_BINNAMES, pAddr, (IntPtr)null); if(nRes < 0) { strError = new Win32Exception(Marshal.GetLastWin32Error()).Message + "["+ strDeviceName +": "+ strPort +"]"; return false; } Notice that there are three calls to DeviceCapabilities in that code. You need all three. (I think the code would be clearer by making each call a separate line of code but that's a style issue.) The doc for DeviceCapabilities plus the sample code above should get you back on track.
Compare time between a log file and an image file
I have 1000's of images and more than 100,000 lines of log files. I need to check if there exists an image that is associated with each unix time in log file. To do this, I first read thru all the images and stored time information in an array. Then I read thru all the lines of the log file, split each information (lat, long, time) and stored them in an array. Finally, I am taking one time element at a time and checking if it matches with image time array. If no match is found, I get the time from log, get lat and long from the same array and write it to a text file. But the overall process takes very long time. I am looking into efficiencies on how to make this process faster. var fileList = Directory.GetFiles(imageLocation, "*.jpg"); //Array that will store all the time information obtained from image property double[] imgTimeInfo = new double[fileList.Length]; int imgTimeCounter =0; foreach (var fileName in fileList) { x++; string fileNameShort = fileName.Substring(fileName.LastIndexOf('\\') + 1); richTextBox1.AppendText("Getting time information from image " + x + " of " + fileList.Length + " : " + fileNameShort + Environment.NewLine); richTextBox1.Refresh(); using (var fs = File.OpenRead(fileName)) { //create an instance of a bitmap image var image = new Bitmap(fs); //get the date/time image property of the image PropertyItem property = image.GetPropertyItem(36867); System.Text.Encoding encoding = new System.Text.ASCIIEncoding(); string valueFrmProperty = encoding.GetString(property.Value); //Format the value obtained to convert it into unix equivalent for comparison string valueCorrected = valueFrmProperty.Split(' ')[0].Replace(":", "/") + " " + valueFrmProperty.Split(' ')[1]; var unixTime = ConvertToUnixTimeStamp(DateTime.Parse(valueCorrected)); imgTimeInfo[imgTimeCounter] = unixTime; imgTimeCounter++; //It is very important to dispose the image resource before trying to read the property of another image. image.dispose frees the resources or else we get //outofmemoryexception. image.Dispose(); } } MessageBox.Show("Images done."); richTextBox1.AppendText("Fetching time information from log files..."+Environment.NewLine); richTextBox1.Refresh(); int counter4Time = contentBathy.Length / 6; //assign counter for lat,long and time int timeCounter = 3; for (int i = 0; i < counter4Time; i++) { richTextBox1.AppendText("Searching time match with image files..." + Environment.NewLine); richTextBox1.Refresh(); double timeValue = Int32.Parse(contentBathy[timeCounter]); //Looks for values that is +- 3 seconds different in the image file. if (Array.Exists(imgTimeInfo, a => a == timeValue || a == timeValue + 1 || a == timeValue + 2|| a == timeValue+3 ||a == timeValue-1|| a== timeValue-2||a == timeValue-3)) { File.AppendAllText(#"c:\temp\matched.txt", "Lat : " + contentBathy[timeCounter - 3] + " Log : " + contentBathy[timeCounter - 2] + Environment.NewLine); richTextBox1.AppendText("Image with same time information found. Looking for another match."+ Environment.NewLine); } else { //richTextBox1.AppendText("Time did not match...Writing GPX cordinates..." + Environment.NewLine); //richTextBox1.Refresh(); File.AppendAllText(gpxLocation, "Lat : " + contentBathy[timeCounter - 3] + " Log : " + contentBathy[timeCounter - 2] + Environment.NewLine); } if(timeCounter < contentBathy.Length-3) timeCounter += 6; } }
Parse unique string from complicated serial data C#
I need to parse this string from serial:- !00037,00055# 00037 as one string, 00055 as another string However this string is came out when the robot's tire is rotated and some other string may also display before and after the string that I need to parse. For example this is the some of the transmission received:- 11,00085#R-STOPR-STOP!00011,00095#!00001,00015#R-STOP!00001,00085#!00003,00075#!00006,00015#R-STOP!00009,00025#!00011,00035#!00011,00085#R-STOPR-STOP!00011,00095#!00001,00015#R-STOP!00001,00085#!00003,00075#!00006,00015#R-STOP!00009,00025#!00011,00035#R-STOP!00001,00085#!00003,00075#!00006,00015#R-STOP!00009,00025#!00011,00035#R-STOP!00037,00055#!00023,00075#R-STOPR-STOP!00022,00065#!00011,00085#R-STOPR-STOP!00011,00095#!00001,00015#R-STOP!00001,00085#!00003,00075#!00006,00015#R-STOP!00009,00025#!00011,00035#R-STOP!00037,00055#!00023,00075#R-STOPR-STOP!00022,00065#!00011,00085#R-STOPR-STOP!00011,00095#!00001,00015# So far I'm stuck at what to do next after SerialPort.ReadExisting() Here is some code to retrieve the serial data:- private void serialCom_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { InputData = serialCom.ReadExisting(); if (InputData != String.Empty) { this.BeginInvoke(new SetTextCallback(IncomingData), new object[] { InputData }); } } catch { MessageBox.Show("Error"); } } and display incoming serial data inside textbox private void IncomingData(string data) { tb_incomingData.AppendText(data); tb_incomingData.ScrollToCaret(); } This code is using .NET Framework 4.0 and Windows Form.
Finally solve it using indexof and substring. private void IncomingData(string data) { //Show received data in textbox tb_incomingData.AppendText(data); tb_incomingData.ScrollToCaret(); //Append data inside longdata (string) longData = longData + data; if (longData.Contains('#') && longData.Contains(',') && longData.Contains('!')) { try { indexSeru = longData.IndexOf('!'); //retrieve index number of the symbol ! indexComma = longData.IndexOf(','); //retrieve index number of the symbol , indexAlias = longData.IndexOf('#'); //retrieve index number of the symbol , rotation = longData.Substring(indexSeru + 1, 5); //first string is taken after symbol ! and 5 next char subRotation = longData.Substring(indexComma + 1, 5); //second string is taken after symbol ! and 5 next char //tss_distance.Text = rotation + "," + subRotation; longData = null; //clear longdata string } catch { indexSeru = 0; indexComma = 0; indexAlias = 0; } } }
You can determine your pattern to transform this string into a array using SPLIT function. This code, send "!00037,00055#" returns two itens: 00037 and 00055. static void Main(string[] args) { string k = "!00037,00055#"; var array = k.ToString().Split(','); Console.WriteLine("Dirty Itens"); for (var x = 0; x <= array.Length - 1; x++) { var linha = "Item " + x.ToString() + " = " + array[x]; Console.WriteLine(linha); } Console.WriteLine("Cleaned Itens"); for (var x = 0; x <= array.Length - 1; x++) { var linha = "Item " + x.ToString() + " = " + CleanString(array[x]); Console.WriteLine(linha); } Console.ReadLine(); } public static string CleanString(string inputString) { string resultString = ""; Regex regexObj = new Regex(#"[^\d]"); resultString = regexObj.Replace(inputString, ""); return resultString; }
Null Refrence Exception Unhandled in my Microprocessor simulator [duplicate]
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();