public string UploadImage(Image image) { // TODO: maybe a global lock while we upload this image? var fileName = RandomKey() + ".jpg"; while (_thumbnailDirectory.FileExists(fileName)) { fileName = RandomKey() + ".jpg"; } try { _thumbnailDirectory.GetFile(fileName).Open(FileMode.Create, stream => image.Save(stream, ImageFormat.Jpeg)); } catch (Exception) { try { // if there was any issue, try to delete the file, if we created if (_thumbnailDirectory.FileExists(fileName)) { _thumbnailDirectory.DeleteFile(fileName); } } catch (Exception) { // the error was more fundamental. // don't do anything with this exception. // let the previous exception be the real one thrown. } throw; } return(fileName); }