grady
grady

Reputation: 12735

Waiting for a method to finish using C#?

I have method which writes a file to the local disk. Another method takes that file and uploads it to a sftp server. The problem is, that the file on the sftp server is empty. This is a small piece of my code:

WriteToLocalFolder(content, filename);
WriteToSftpServer(filename, server logon params);

Could it be that WriteToSftpServer gets called before WriteToLocalFolder finished writing? If yes, how can I say that WriteToSftpServer should start only after WriteToLocalFolder has finished writing the file?

WriteToLocalFolder looks like this in the real code:

 public static void WriteToFolder(StringBuilder content, string whereTo)
 {
    File.WriteAllText(whereTo, content.ToString());
 }

So the stream is closed I think...

Thanks :-)

Upvotes: 1

Views: 703

Answers (4)

Goliasse
Goliasse

Reputation: 1

do
  {
     WriteToLocalFolder(content, filename);

  } while ((System.IO.File.Exists(filename) != true));


WriteToSftpServer(filename, server logon params);

this loop will ensure that the file exists with its content befor getting to the next line..

Upvotes: 0

PedroC88
PedroC88

Reputation: 3829

The code in WriteToSftpServer shouldn't ever happen before WriteToLocalFolder is done (because it does not seem to be async). However it could be that filestream is not properly closed and so WriteToSftpServer can't access it.

Try getting a breakpoint inside WriteToSftpServer where the file gets loaded to see what does it load. You can always "step next" inside the method, if the file loads correctly, to see where does it break.

Upvotes: 2

Aistina
Aistina

Reputation: 12683

It depends on the code in WriteToLocalFolder, but it sounds more likely that you're writing content to the file and forgetting to Flush the write buffer. If this is not the case, please edit your question and add the code for WriteToLocalFolder.

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

If WriteToLocalFolder doesn't spawn a separate thread, this is NOT possible. Maybe you are missing a Stream.Flush, Stream.Close or Stream.Dispose in any of the methods?

Upvotes: 0

Related Questions