Reputation: 332
My issue is that I can't have the XML's file name be saved based on the text of a given field: here is the line:
XmlTextWriter writer = new XmlTextWriter(@"{0}\ops\op-" + OpName.Text.Replace(" ", "_") + ".xml",
System.Text.Encoding.UTF8);
The issue I get is that it can't find the path: C:\[stuff]\{0}\op\op-.xml
and if I remove the {0}
(in the code) I get can't find C:\op\op-.xml
I am needing it to find C:\[stuff]\op\
so it can make the file in that folder.
How could I change this line?
Upvotes: 0
Views: 427
Reputation: 3261
string additionalStr=OpName.Text.Replace(" ", "_");
if (string.IsNullOrEmpty(additionalStr))
{
return;
//or throw error or make default file name depending on the required logic
}
string directoryPath=String.Format(@"{0}\ops\",dirPrefix);
bool isDirectoryExists=Directory.Exists(directoryPath);
if (!isDirectoryExists){
//required logic. for example set default directory
}
string fileName=additionalStr+".xml";
string filePath=Path.Combine(directoryPath,fileName);
XmlTextWriter writer = new XmlTextWriter(filePath,System.Text.Encoding.UTF8);
Upvotes: 0
Reputation: 31454
What does {0}
represents in your path? XmlTextWriter
constructor takes file path, not a formatted string. It would be much more readable if you'd prepare your file path in steps, eg. by utilizing Path.Combine method:
var fileName = string.Format("op-{0}.xml", OpName.Text.Replace(" ", "_"));
var rootDir = /* this would be {0} from your original example */
var filePath = Path.Combine(rootDir, "ops", fileName);
XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
Upvotes: 2