Reputation: 1068
My .NET Windows application has multiple instances of being able to open and view text files. I have no problem getting this to work when I create individual openFileDialogs through my code. In trying to clean up my code, I created a method, but I am fairly new and am getting a red squiggly. Can someone please look at this and tell me what I am doing wrong? Thanks.
I am trying to call the method as shown here:
textBox_ViewFile.Text = LoadFromFile();
Then my method is as follows:
static string[] LoadFromFile()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.RestoreDirectory = false;
openFileDialog1.ShowHelp = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if (openFileDialog1.OpenFile() != null)
{
return (File.ReadAllLines(openFileDialog1.FileName));
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
In this case, I am getting a syntax error in VS2010 under "LoadFromFile()" from
static string[] LoadFromFile()"
Upvotes: 1
Views: 3077
Reputation: 1478
You're missing a return
statement if either of your if
statements are false
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if (openFileDialog1.OpenFile() != null)
{
return (File.ReadAllLines(openFileDialog1.FileName));
}
// missing
return null;
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
// missing
return null;
}
}
// missing
return null;
Upvotes: 2
Reputation: 65117
textBox_ViewFile.Text
is a string
. Your function returns an array (string[]
). You need to make the function return a single string
.
return string.Join('\n', File.ReadAllLines(openFileDialog1.FileName));
Or:
return File.ReadAllText(openFileDialog1.FileName);
Upvotes: 1