dt192
dt192

Reputation: 1013

Conditional 'using'

I have the following code that does some conversion from one file to a memory stream which I then write to disk. All is working fine, however I now want to still always open file_1 for reading, but either open memory_stream or file_2 for writing based on user preference.

How can I get a conditional statement working in this situation given the braces will clash.

Thanks in advance for any help.

public static void ProcessFile()
{
   try
   {         
      using (Open file_1 for reading)
      using (Open memory_stream for writing)
      {
         ...

Upvotes: 2

Views: 1829

Answers (3)

Sweeper
Sweeper

Reputation: 271875

I think you should create separate methods for doing those two things. You should also have a method that handles the writing. These should not all be done by ProcessFile.

private static void WriteToFile2() {
    using (FileStream s = ...) { WriteToStream(s); }
}

private static void WriteToMemory() {
    using (MemoryStream s = ...) { WriteToStream(s); }
}

private static void WriteToStrem(Stream s) {
    ...
}

public void ProcessFile() {
    using (FileStream s = ...) { // file 1
        ...
        if (...) {
            WriteToFile2();
        } else {
            WriteToMemory();
        }
    }
}

Upvotes: 0

Michał Turczyn
Michał Turczyn

Reputation: 37367

First of all using is just syntactic sugar for try...finally, where in finally Dispose method of IDisposable object (used in using) is called, so something like

try
{
  using(...){...}
}

makes little sense, as it will be seen as

try
{
  try{...}
  finally{dispose of an object}
}

I think you problem is simple, just do:

if(user preference)
{
  using(writing){...}
}
else
{
  using(reading){...}
}

Upvotes: 0

Theodor Zoulias
Theodor Zoulias

Reputation: 43553

Something like that?

public static void ProcessFile()
{
    using (Open_file_1_for_reading)
    {
        if (condition)
        {
            using (Open_memory_stream_for_writing)
            {
                // ...
            }
        }
    }
}

Upvotes: 2

Related Questions