creating a directory during runtime

G

Guest

hi!

i am able to upload files successfully. but i have one minor problem. files
are uploaded correctly if the directory exists, it is throwing an exception
if the directory doesnt exist. but the directory name is created during
runtime. is there a way to create a directory during runtime?

exception:
Error saving file C:\temp\188\
System.IO.DirectoryNotFoundException: Could not find a part of the path
"C:\temp\188\_ds27.tmp". at System.IO.__Error.WinIOError(Int32 errorCode,
String str) at System.IO.FileStream..ctor(String path, FileMode mode,
FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync,
String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String
path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at
mole.proposals.dltaskorders.addTaskOrder.btnUpload_Click(Object sender,
EventArgs e) in c:\inetpub\wwwroot\dltaskorders\addtaskorder.aspx.cs:line 286

code:
private void btnUpload_Click(object sender, System.EventArgs e)
{
string baseLocation = "C:\\temp\\" + Session["sReference"].ToString()
+ "\\";
string status = "";


if((lstAttachments.Items.Count == 0) && (filesUploaded == 0))
{
lblError.Text = "Error - a file name must be specified.";
return;

}
else
{
foreach(System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
{
try
{
string fn =
System.IO.Path.GetFileName(HIF.PostedFile.FileName);
HIF.PostedFile.SaveAs(baseLocation + fn);
filesUploaded++;
status += fn + "<br>";
}
catch(Exception err)
{
lblError.Text = "Error saving file " + baseLocation
+ "<br>" + err.ToString();
}
}

if(filesUploaded == hif.Count)
{
lblError.Text = "These " + filesUploaded + " file(s) were "
+ "uploaded:<br>" + status;
}
hif.Clear();
lstAttachments.Items.Clear();
}
}
 
R

Ruben Silva PT

Hi!!!

I had a similar problem and i solve it using the following lines:


string folder = Path.GetDirectoryName(path);
if(!Directory.Exists(folder))
{
try
{
Directory.CreateDirectory(folder);
}
catch(Exception ex)
{
EventLog.WriteEntry("LogService", ex.Message,
EventLogEntryType.Error);
}
}

I hope it solves your problem.
 
N

Nicholas Paldino [.NET/C# MVP]

Newbie,

You should be able to get the directory in the filename using the static
GetDirectoryName method on the Path class. Then, you can pass that to the
static CreateDirectory method on the Directory class to create the directory
before you save the file.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top