Reputation: 6615
I am trying to create a file in a user folder and populate it with some basic text. seems simple, but i keep getting an error:
Could not find a part of the path 'C:\websites\admin\upload\users\testuserID\testuserIDSampleRecord.txt'."} System.Exception {System.IO.DirectoryNotFoundException}
my website is located under: c:\websites\testsite\
, so the full path should be:
c:/websites/testsite/admin/upload/users/
the IIS localhost is set to point to c:/websites/
so when i run it i type localhost/testsite
to get to it
here is what i have:
try
{
string SampleCaseText = BuildTextRecord();
string username = (string)Session["userid"];
string folderPath = "/testsite/admin/upload/users/" + username;
bool IsExists = System.IO.Directory.Exists(Server.MapPath(folderPath));
if(!IsExists)
System.IO.Directory.CreateDirectory(Server.MapPath(folderPath));
System.IO.File.Create(folderPath + "/" + username + "SampleRecord.txt");
File.WriteAllText(Path.Combine(folderPath, username + "SampleRecord.txt"), SampleCaseText);
}
it created the new folder testuserID in the correct place, but it fails when trying to create/write the file.
Upvotes: 1
Views: 5396
Reputation: 21
Here is something that may help - to make it a bit easier I did not include code that creates a file or a folder, but simply to grab an existing file, open it and write to it.
Hopefully this gives some direction and you can go from there.
private void Error(string error)
{
var dir= new DirectoryInfo(@"yourpathhere");
var fi = new FileInfo(Path.Combine(dir.FullName, "errors.txt"));
using (FileStream fs = fi.OpenWrite())
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(error);
sw.Close();
sw.Dispose();
}
}
One thing to note: make sure you have permissions on the folder and file you wish to write to.
Upvotes: 0
Reputation: 19963
There are a couple of errors that I see off hand that could be causing trouble...
Firstly instead of using the web /
folder delimiter, use the windows \
one instead.
Secondly, you're not using Server.MapPath
in all the location you should be... resulting in using the web relative path instead of the local windows path.
Try something like this, where I've convert the folder to a windows path at the start, and put the converted userFilename
into it's own variable, and used that instead...
string folderPath = Server.MapPath("/testsite/admin/upload/users/" + username);
bool IsExists = System.IO.Directory.Exists(folderPath);
if(!IsExists)
System.IO.Directory.CreateDirectory(folderPath);
string userFilename = Path.Combine(folderPath, username + "SampleRecord.txt");
System.IO.File.Create(userFilename);
File.WriteAllText(userFilename, SampleCaseText);
Upvotes: 1