简体   繁体   English

C#中的XMLWriter问题

[英]XMLWriter issues in C#

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: 我的问题是我不能根据给定字段的文本保存XML的文件名:这是行:

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 我得到的问题是,它无法找到路径: C:\\[stuff]\\{0}\\op\\op-.xml ,如果我删除了{0}代码)我得到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. 我需要它来找到C:\\[stuff]\\op\\所以它可以使该文件夹中的文件。

How could I change this line? 我怎么能换这条线?

What does {0} represents in your path? {0}在您的路径中代表什么? XmlTextWriter constructor takes file path, not a formatted string. XmlTextWriter构造函数采用文件路径,而不是格式化字符串。 It would be much more readable if you'd prepare your file path in steps, eg. 如果你准备好步骤中的文件路径,那将会更具可读性,例如。 by utilizing Path.Combine method: 通过使用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);
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM