Question

I am learning F#, so I have been coming up with small blocks of code to help me get the hang of the language. I created the code below to be called from C# and subsequently save an uploaded file. How can I improve this code? All points of views are welcome.

open System.Web
open System.IO

type SaveUpload(file: HttpPostedFileBase, path : string) = 

    // get the file name
    let origFileName = file.FileName

    // create the path including filename
    let filePath = Path.Combine(path, origFileName)

    // directory check
    let directory = Directory.Exists(path)

    // create directory
    let createDir x = 
        match x with
        |false -> Directory.CreateDirectory(path) |> ignore
        |true -> ()

    // save file
    let saveFile = 
        createDir directory
        if directory 
        then file.SaveAs(filePath)
Was it helpful?

Solution

Here are some quick thoughts:

  • As you wrote it, the code is defining a type SaveUpload, but you are really implementing code that does some work - so I do not see why this would be a type. You can write it as a static member or a function (both will look as static methods to C#)

  • I'm not sure if pattern matching on Booleans using match is really that useful here. It might be shorter to just use if (but pattern matching is great in more advanced cases)

  • At the end, you are defining a variable saveFile, but this is just a value of type unit - all the code is already executed and the file is saved when someone calls the constructor. If you intended to make this a method, then it needs to take a unit value () as an argument.

  • Similarly, directory is a value that is calculated just once - and so if the directory does not exist, your code creates it, but then does not save the file, because the directory value is still false.

So, if I wanted to write this as a function in a module, I'd go with something like this:

open System.Web
open System.IO

module FileHelpers = 
  let SaveUpload (file:HttpPostedFileBase) (path:string) = 

    // get the file name
    let origFileName = file.FileName

    // create the path including filename
    let filePath = Path.Combine(path, origFileName)

    // directory check
    let pathExists () = Directory.Exists(path)

    // create directory
    let createDir () = 
        if not (pathExists ()) then
            Directory.CreateDirectory(path) |> ignore

    // save file
    createDir ()
    if pathExists() then
        file.SaveAs(filePath)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top