I am still struggling with my first program in C#. I need to first select a file from a directory, second, open the file, and third load an array with the contents of the file.
This array will later be used to send bytes to an external device (a test fixture) via USB. I can't seem to find the code to get the information into a form that I can use.
Add a menuStrip and an openFileDialog to your form from the toolbox.
Add an 'Open File' tool strip menu item.
Your code for selecting the file to open may be something like this:
private void OpenFileToolStripMenuItem_Click(object sender, System.EventArgs.e)
// Open the file.
// Begin in the project folder.
openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
// Display the File Open dialog box.
responseDialogResult = openFileDialog1.ShowDialog();
if (responseDialogResult != DialogResult.Cancel)
// User did not select cancel so open the file.
StreamReader fileReader = new Streamreader(openFileDialog1.Filename);
// For a simple array you could use a while loop
string fileString = "";
int indexInteger = 0;
// Your array, myArray, has been previously declared.
while ( fileString != null)
fileString = fileReader.ReadLine();
if ( fileString != null)
myArray[indexInteger++] = fileString;
// If your array is a two-dim array you could use a for loop as such
for(int rowi = 0; rowi < 2; rowi++)
for(int coli = 0; coli < 4; coli++)
myArray[rowi, coli] = fileReader.ReadLine();
You can also use the ReadAllText or ReadAllLines of the File Class to load your array from a file:
// Read file into array with ReadAllLines.
string myArray = File.ReadAllLines(openFileDialog1.FileName);
// Raed file into array with ReadAllText.
string myArray = File.ReadAllText(openFileDialog1.Filename);
// With ReadAlltext you have to split the long string into individual strings.
string aString = myArray.Split('\n');
Many thanks to Chellam2. This helped out quite a lot. Now my problem is to be able to access the array from another part of the program. At first attempt, the error I get is that the array does not exist in the current context. It tried replacing the "void" word with "int" and add a return statement. Then I get an error stating that the object has the wrong return type. I tried all different return types to no avail. Stuck again.
Ditto above post. You need to perhaps read up on the scope of variables. Likely you've declared your array at block level and it's therefore not available to other methods.
Try declaring your array at the class-level so that all methods of the class have access to it.
Again, thanks. I think I am beginning to get to hang of the program now. I know that I still have a long way to go, but it looks like this one program is beginning to fall into place. I will post another thread if I bump into another roadblock.
Thnaks, thanks, thanks