Domanda

I recently wrote some code related to a menu strip bar, there is an option contains OpenFile, SaveFile and Exit etc. Following is the code.

Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True
    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        Try
            myStream = saveFileDialog1.OpenFile()
            If (myStream IsNot Nothing) Then
                ' Code to write the stream goes here.
                Dim sw As New StreamWriter(myStream)

                sw.Flush()
                sw.Close()

                myStream.Close()
             End If
         Catch Ex As Exception
             MessageBox.Show("Can't save file on disk: " & Ex.Message)
         End Try
    End If

another chunk of code exactly same but withou If statement, as following,

Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True

    Try
        myStream = saveFileDialog1.OpenFile()
        If (myStream IsNot Nothing) Then
            ' Code to write the stream goes here.
            Dim sw As New StreamWriter(myStream)
            'some sw.WriteLine code here...            
            sw.Flush()
            sw.Close()

            myStream.Close()
         End If
     Catch Ex As Exception
         MessageBox.Show("Can't save file on disk: " & Ex.Message)
     End Try

The problem I have is the second piece of code, when it runs the system will throw out index out of range exception, How can I fix it without using a If statement? Is there any method to show the dialog window anyway? Anyone can give me clue on this index error message? Thanks!

È stato utile?

Soluzione

Looking at the source code of OpenFile reveals the possible point of error

public Stream OpenFile()
{
    IntSecurity.FileDialogSaveFile.Demand();
    string str = base.FileNamesInternal[0];
    if (string.IsNullOrEmpty(str))
    {
        throw new ArgumentNullException("FileName");
    }
    Stream stream = null;
    new FileIOPermission(FileIOPermissionAccess.AllAccess, IntSecurity.UnsafeGetFullPath(str)).Assert();
    try
    {
        stream = new FileStream(str, FileMode.Create, FileAccess.ReadWrite);
    }
    finally
    {
        CodeAccessPermission.RevertAssert();
    }
    return stream;
}

It seems that the code try to get the base.FileNamesInternal[0]; but if you don't show the dialog or choose a file name to save this internal array is probably empty.

I have tried to read the item at index zero in the property FileNames and I get the same error

string file = saveFileDialog1.FileNames(0)  ' Index out of range....

I would like to hear from our WinForms more experienced posters if this is really what it seems

Altri suggerimenti

I guess I'm a bit confused about what you are trying to accomplish.

In the second example it seems you never 'show the dialog' ie saveFileDialog1.ShowDialog()

Thus the user cannot select a file/path

Then you attempt to use the file/path that has not been set

http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.openfile.aspx

If you just need to open an arbitrary file for write without showing the user the dialog why not just use File.Open() or something?

http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top