Masriyah
Masriyah

Reputation: 2505

checking to see if Stream inputStream File exists or not

I am changing a method that used to accept string for temp folder and string for file and changing it to a stream and i wanted some help how to check if file exists or not.

bool UploadFile(Stream inputStream, Stream inputFile);

This is what i originally had and i want to change so the parameters accepts a stream

bool UploadFile(string tempFolder, string fileName)

public bool UploadFile(string tempFolder, string fileName)
        {
            if (File.Exists(fileName))
            {
                testingUsage.Upload(tempFolder, fileName);  
                return testingUsage.Exists(tempFolder);
            }

            return false;
        }

do i create two streams one for the file and one for location?

Upvotes: 1

Views: 2578

Answers (1)

ataravati
ataravati

Reputation: 9155

Assuming this is your Upload Action:

[HttpPost]
public ActionResult Upload()
{
    try
    {
        if (Request.Files.Count > 0)
        {
            string tempFolder = "...";
            var file = Request.Files[0];

            if(UploadFile(tempFolder, file))
            {
              // Return a View to show a message that file was successfully uploaded...
              return View();
            }   
        }
    }
    catch (Exception e)
    {
        // Handle the exception here...
    }
}

Your Method can be something like this:

private bool UploadFile(string tempFolder, HttpPostedFileBase file)
{
   var path = Path.Combine(tempFolder, file.FileName);

   // if the file does not exist, save it.
   if (!File.Exists(path))
   {
      file.SaveAs(path);
      return true;
   }

   return false;
}

Upvotes: 1

Related Questions