0

我的问题是我不能根据给定字段的文本保存 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\,以便它可以在该文件夹中创建文件。

我怎么能改变这条线?

4

2 回答 2

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);
于 2012-12-02T11:33:28.507 回答
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);
于 2012-12-02T11:30:22.880 回答