XMLWriter issues in C# - 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:
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?

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);

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);

Related

C#. Writing settings to XML file

I have some names of files. I am creating a XML file to store them. When application runs second time it should recognize those file names. Here is my code:
XmlWriter writer = XmlWriter.Create("settings.xml");
writer.WriteStartElement("DialogCreater");
writer.WriteElementString("conditionsFile", conditionsFile);
writer.WriteEndElement();
writer.Close();
But when I use those file names like this:
string[] lines = File.ReadAllLines(charactersFile);
It gives me an error.
System.NotSupportedException
Here how I read them from XML file:
XmlDocument doc = new XmlDocument();
doc.Load("settings.xml");
XmlNodeList node = doc.GetElementsByTagName("files");
foreach (XmlNode n in node[0].ChildNodes)
{
if (n.Name == "conditionsFile") conditionsFile = n.InnerText;
}
NotSupportedException
path is in an invalid format according to msdn documentation. you can fix it by checking path exist or not before reading from itMore info
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
//file exist
}

How to add header and footer txt file in C#?

I want to add a header and footer inside of my text file. How can i do that? My target should like This:
tr.AddHeaderAndFooter("Header","footer";
For example:
using (var fileStream = new FileStream(ConfigurationManager.AppSettings["TargetDir"] + swiftFile, FileMode.Open, FileAccess.Read))
{
TextReader tr = new StreamReader(fileStream);
tr.AddHeaderAndFooter("Header","footer";
}
A .txt file does not have a header or footer.
But you can simulate this behaviour with the following code sample:
// since there is no predefined method to add a string into the beginning
// of a file, you have to first read the whole file content into a temporary
// variable
string currentContent = String.Empty;
if (File.Exists(filePath))
{
currentContent = File.ReadAllText(filePath);
}
// now you can put your header into the beginning of the file so:
string header = "My Header";
File.WriteAllText(filePath, header + Environment.NewLine + currentContent );
// and finally you use the append method to add footer to the end of the file
string footer = "My Footer";
File.AppendAllText(filepath, Environment.NewLine + footer);
Do you mean something along the lines of:
string text = "header" + Environment.NewLine + "rest of file ... asjdhakjdh" + Environment.NewLine + "footer";
File.WriteAllText("filename.txt", text);
This will save
header
rest of file ... asjdhakjdh
footer
in a .txt file named filename.txt
So you could read your file, store it in a string, add your header and footer line and write it back to the same file it came from.

Display properties of an XML file using XmlTextWriter

I have created an xml file using the following code:
XmlTextWriter write = new XmlTextWriter(FileName, null);
write.Formatting = Formatting.Indented;
write.WriteStartDocument();
write.WriteComment("Its Xml Document");
write.WriteStartElement("CollegeInformation");
write.WriteStartElement("StudentDetails");
write.WriteElementString("stdID", "1001");
write.WriteElementString("StudentName", "XYZ");
write.WriteEndElement();
write.WriteEndElement();
write.WriteEndDocument();
write.Close();
Now I want to display the properties of this xml file like name, file size, length on console.
How can I do that ?
Use can use FileInfo class to get the file properties.
System.IO.FileInfo f = new System.IO.FileInfo(FileName);
Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
Click on below link to get the properties available with the FileInfo Class.
http://msdn.microsoft.com/en-us/library/system.io.fileinfo_properties%28v=vs.110%29.aspx

Illegal characters in path c# - XmlTextWriter

I am using XmlTextWriter and get an error while loading URL from rest service. The error is "illegal characters in path". I have tried using #"https://www.foo.com/foobar/rest-1/Data/Test?sel=GeneratedFrom&find=TS-01108&findin=Parent.Number"
When I step through with debugger I see the value has quotations, but I suspect it might be either the "?", "=", "&" or "." perhaps.
string URL = "https://www.foo.com/foobar/rest-1/Data/Test?sel=GeneratedFrom&find=TS-01108&findin=Parent.Number";
string XML_FILENAME = URL + ".xml";
WebResponse response = utils.GetRestResponse(URL);
if (response != null)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(XmlReader.Create(response.GetResponseStream()));
// Illegal characters in path happens here
XmlTextWriter writer = new XmlTextWriter(XML_FILENAME, null);
I think you misunderstand the purpose of the first XmlTextWriter initializer parameter. If a string parameter is passed there, that should be a filename not a web resource.
https://www.foo.com/foobar/rest-1/Data/Test?sel=GeneratedFrom&find=TS-01108&findin=Parent.Number
Is not a legal file name, change it to something else. When the xml file is written to the disk it needs a legal name, your name is contains illegal characters. Try to create a text file with that name and windows will complain.

Convert blank .txt file to PDF in C#

I am converting a .txt to .pdf in c#. This works fine if the .txt file is not blank. if it is, it threw an error of "The document has no pages".
The pdf gets generated but threw an error of "There was an error opening this document. The file is damaged and could not be repaired" when opening a pdf file.
Code is seen below
public void converttxttoPDF(string sourcePath, string destPath)
{
try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
string filename = Path.GetFileNameWithoutExtension(sourcePath);
System.IO.StreamReader myFile = new System.IO.StreamReader(sourcePath);
string myString = myFile.ReadToEnd();
myFile.Close();
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
document.Open();
document.Add(new iTextSharp.text.Paragraph(myString));
document.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
let me know if any info needed.
thanks
You need to add some content to the pdf. So try this:
myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));
You need to convince iText that there IS something on that page.
Two Methods:
Be explicit. writer.setPageEmpty(false);
Trick it (which is what Darin suggests). writer.getDirectContent().setLiteral(" ");

Categories