Create file and directory
We can use System.IO.Directory.CreateDirectory
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.
// Creating Directory using static methods in class FlowHelper
string folderPath = Server.MapPath("/FileUpload");
FlowHelper.CreateDirectoryIfNotExists(folderPath);
// Saving file to given folder
string ext = Path.GetExtension(postedFile.FileName);
if (ext == ".jpg" || ext == ".png" || ext == ".jpeg" || ext == ".gif")
{
string filePath = "";
filePath = "/FileUpload/" + "abc" + ext;
string path = Server.MapPath(filePath);
postedFile.SaveAs(path);
}
// Deleting file using static method in class FlowHelper
bool fileDeleted = FlowHelper.TryToDeleteFile(path);
public class FlowHelper
{
public static bool CreateDirectoryIfNotExists(string folderPath)
{
try
{
bool folderExists = Directory.Exists((folderPath));
if (!folderExists)
{
Directory.CreateDirectory((folderPath));
return true;
}
else
{
return true;
}
}
catch
{
throw;
}
}
public static bool TryToDeleteFile(string filePath)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
return true;
}
else
{
return false;
}
}
catch
{
throw;
}
}
}
No comments:
Post a Comment