Domanda

I have such code that saves bin file, but user has to choose file

         Stream myStream;
         SaveFileDialog saveFileDialog1 = new SaveFileDialog();

        saveFileDialog1.Filter = "Binary File (*.bin)|*.bin";
        saveFileDialog1.FilterIndex = 2;
        saveFileDialog1.RestoreDirectory = true;

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((myStream = saveFileDialog1.OpenFile()) != null)
            {
                Question.PersistObject(questions, myStream);
                myStream.Close();
            }
        }

But I want to choose file in code, and if a file with such name doesn't exist, then create it. How to set in myStream that file?

È stato utile?

Soluzione

Replace all your logic related to the OpenFileDialog with File.Open:

using (var myStream = File.Open(someFilePath, FileMode.OpenOrCreate))
{
    Question.PersistObject(questions, myStream);  // do something with the stream
}

The OpenOrCreate file mode will open the file if it exists, or create it if it does not.

The using statement will take care of closing the stream for you.

Altri suggerimenti

One option would be to have a base name and append a number:

string templateName = "myfile{0}.bin";
string finalName;
int count = 0;
do {
    finalName = String.Format(templateName, count++);
} while (File.Exists(finalName);

Or, if you don't care about the name, use Path.GetTempFileName

Then pass that name to StreamWriter:

 using (StreamWriter writer = new StreamWriter(finalName))
 {
      // Write stuff
 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top