Reputation: 6335
I'm trying to put all of these strings together into a path for my program to save a document in. Nothing fancy. but every time I go to save the file in debugging, it will create a folder named after the file and do nothing else. I feel like this is a simple issue, but I cant find how to fix it. Help please!
my code
private void btnSave_Click(object sender, EventArgs e)
{
string strNotes = rtbNotes.Text.ToString();
string strUser = txtUser.Text.ToString() + "\\";
string strClass = txtClass.Text.ToString() + "\\";
string strDate = DateTime.Today.Date.ToString("dd-MM-yyyy");
string strLocation = "C:\\Users\\My\\Desktop\\Notes\\";
string strType = txtType.Text.ToString();
string strFile = strLocation + strUser + strClass + strDate;
string subPath = strFile + "." + strType;
bool isExists = System.IO.Directory.Exists(subPath);
if (!isExists)
System.IO.Directory.CreateDirectory(subPath);
System.IO.File.WriteAllText(strFile, strNotes);
}
Upvotes: 1
Views: 2647
Reputation: 2941
Firstly, your strLocation path is invalid:
C:\Users\My\Desktop\Notes\
Secondly you are passing entire file path (including file name / extension) into Directory.Exists so its actually checking to see to see if a folder named "12/12/13.txt" exists (you should simply pass the folder path).
You are then trying to write a file but passing what should be a directory path...
Are you using a debugger to step through your code? This would help.
private void button1_Click(object sender, EventArgs e)
{
string strNotes = "Some test notes.";
string strUser = "someuser" + "\\";
string strClass = "SomeClass" + "\\";
string strDate = DateTime.Today.Date.ToString("dd-MM-yyyy");
string strLocation = "C:\\Users\\My\\Desktop\\Notes\\";
string strType = "txt";
string strFile = strLocation + strUser + strClass + strDate; // ... this is: C:\Users\My\Desktop\Notes\
string subPath = strFile + "." + strType; // .. this is: C:\Users\My\Desktop\Notes\someuser\SomeClass\26-10-2013.txt
bool isExists = System.IO.Directory.Exists(subPath); // ... Checks directory: C:\Users\My\Desktop\Notes\ exists...
if (!isExists)
System.IO.Directory.CreateDirectory(subPath); // ... Creates directory: C:\Users\My\Desktop\Notes\ ...
System.IO.File.WriteAllText(strFile, strNotes); // ... Writes file: this is: C:\Users\My\Desktop\Notes\26-10-2013 ...
}
Upvotes: 1
Reputation: 11442
You need to debug and watch the value of subPath. It looks like this is being set to the value of your intended file name but without the extension.
I think you should have had
string subPath = strLocation + strUser + strClass + strDate;
string strFile = subPath + "." + strType;
Upvotes: 0