Best way to check File write permission of Asp.net


There are many methods to check file write permission on Asp.net shared hosting. Quickest and easiest method for this purpose is creating a file and deleting that for this purpose.

Here is sample method to do this

/// <summary>
/// Helper method to quickly check if directory or file is writable
/// </summary>
/// <param name="url">Physical path</param>
/// <param name="file">Optional File name</param>
/// <returns>True if application can write file/directory</returns>
public static bool CanWrite(string url, string file = "")
{
    var dir = HttpContext.Current.Server.MapPath(url);

    if (dir != null && Directory.Exists(dir))
    {
        if (string.IsNullOrEmpty(file)) 
            file = string.Format("test{0}.txt", DateTime.Now.ToString("ddmmhhssss"));

        try
        {
            var p = Path.Combine(dir, file);

            using (var fs = new FileStream(p, FileMode.Create))
            using (var sw = new StreamWriter(fs))
            {
                sw.WriteLine(@"test");
            }

            File.Delete(p);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
    return false;
}