我的问题是我不能根据给定字段的文本保存XML的文件名:这是行:
XmlTextWriter writer = new XmlTextWriter(@"{0}\ops\op-" + OpName.Text.Replace(" ", "_") + ".xml",
System.Text.Encoding.UTF8);
我得到的问题是它无法找到路径:C:\[stuff]\{0}\op\op-.xml
如果我删除{0}
(在代码中),我会can't find C:\op\op-.xml
我需要它来查找C:\[stuff]\op\
,以便它可以在该文件夹中生成文件。
我怎么能改变这条线?
答案 0 :(得分:2)
{0}
在您的路径中代表什么? XmlTextWriter
构造函数采用文件路径,而不是格式化字符串。如果你准备好步骤中的文件路径,那将会更具可读性,例如。利用Path.Combine方法:
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);
答案 1 :(得分:0)
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);