X document overwriting the existing file in c# - c#

var filename = "C:\\Users\\qadeer.hussain\\Desktop\\gw-msg.log";
var xmlText = new StringBuilder();
bool isXml = false;
foreach (var line in System.IO.File.ReadLines(filename))
{
if (line.Trim().StartsWith("<Message"))
isXml = true;
if (isXml)
{
xmlText.Append(line);
if (line.Trim().EndsWith("</Message>"))
{
//Response.Write(xmlText.ToString());
var xdoc= XDocument.Parse(xmlText.ToString());
xdoc.Save("C:\\Users\\qadeer.hussain\\Desktop\\gw-msg-2.log");
xmlText.Clear();
isXml = false;
}
}
}
i am getting xml data from log file now i have a many xml tag and i am reading that tag when is read a tag i save it into file but the problem is every time my file is overwritten i want my file is not overwritten

using(var writer = File.CreateText(YOUR_FILE_NAME)))
{
....
foreach (var line in System.IO.File.ReadLines(filename))
{
...
//replace xdoc.Save(YOUR_FILE_NAME)
writer.WriteLine(xdoc.ToString());
}
}
By the way. The document you get will not be a valid XML docuemnt. It will be a series of concatinated valid XML documents.

Related

How can I extract xml file encoding using streamreader?

I needed to get the encoding type from the top of the xml file
<?xml version=“1.0” encoding=“utf-8”?>
but only the encoding="utf-8" is needed
the "utf-8" only without the quotation mark, how can I achieve this using streamreader?
You need utf-8 or encoding="utf-8" ? this block returns utf-8 as a result. If you need encoding="utf-8", you need to change.
using (var sr = new StreamReader(#"yourXmlFilePath"))
{
var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
using (var xmlReader = XmlReader.Create(sr, settings))
{
if (!xmlReader.Read()) throw new Exception("No line");
var result = xmlReader.GetAttribute("encoding"); //returns utf-8
}
}
Since it's xml, I would recommend XmlTextReader that provides fast, non-cached, forward-only access to XML data and read just top of the xml file since declaration is there. See following method:
string FindXmlEncoding(string path)
{
XmlTextReader reader = new XmlTextReader(path);
reader.Read();
if (reader.NodeType == XmlNodeType.XmlDeclaration)
{
while (reader.MoveToNextAttribute())
{
if (reader.Name == "encoding")
return reader.Value;
}
}
return null;
}
how can I achieve this using StreamReader?
Something like this:
using (StreamReader sr = new StreamReader("XmlFile.xml"))
{
string line = sr.ReadLine();
int closeQuoteIndex = line.LastIndexOf("\"") - 1;
int openingQuoteIndex = line.LastIndexOf("\"", closeQuoteIndex);
string encoding = line.Substring(openingQuoteIndex + 1, closeQuoteIndex - openingQuoteIndex);
}
const string ENCODING_TAG = "encoding"; //You are searching for this. Lets make it constant.
string line = streamReader.ReadLine(); //Use your reader here
int start = line.IndexOf(ENCODING_TAG);
start = line.IndexOf('"', start)+1; //Start of the value
int end = line.IndexOf('"', start); //End of the value
string encoding = line.Substring(start, end-start);
NOTE: This approach expects the encoding to be in the first line of an existing declaration. Which it does not need to be.

Can't load XML from Resource/Drawable/

I've saved my Xml in Resource/Drawable/ . I put it here cause is the only place where it can stay without any error.
Any way this is the exception:
System.IO.FileNotFoundException: Could not find file "/sds".
How can I find the path?
Here is my code:
String conditionName = "";
XDocument xml = XDocument.Load("#drawable/LightConditions.xml");
foreach (XElement item in xml.Root.Elements("Condizione"))
{
if (item.Element("EV").Value == EV)
{
conditionName = item.Parent.Element("Nome").Value;
break;
}
//do something
}
You will want to place that .xml in the Assets folder and flag the build action as an AndroidAsset.
Then you can use the AssetManager to access it via a Stream:
string conditionName = "";
using (StreamReader sr = new StreamReader(this.Assets.Open("LightConditions.xml")))
{
XDocument xml = XDocument.Load(sr);
foreach (XElement item in xml.Root.Elements("Condizione"))
{
if (condizione.Element("EV").Value == EV)
{
conditionName = item.Parent.Element("Nome").Value;
break;
}
//do something
}
}
Consult the Xamarin.Android guide on Assets

xdocument re writing xml document [duplicate]

I have a method which load XML to a XDocument and modify its elements then save.
But when I reload it. I got this error :
Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.
I checking the XML and see that the XDocument didn't save the changed but create a duplicate and save.
It save the old one and the new one like this example xml :
<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
<Ungdung>
<Name>HERE City Lens</Name>
<Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
<Path>/Icon/herecitylens.png</Path>
<Version>Unknown</Version>
<Category>HERE</Category>
<Date>Uknown</Date>
</Ungdung>
<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
<Ungdung>
<Name>HERE City Lens</Name>
<Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
<Path>/Icon/herecitylens.png</Path>
<Version>1.0.0.0</Version>
<Category>HERE</Category>
<Date>Uknown</Date>
</Ungdung>
Here the code I used to modify and save XML :
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Open, FileAccess.ReadWrite))
{
//var xdoc = XDocument.Load("APPSDATA.xml");
var xdoc = XDocument.Load(stream, LoadOptions.None);
var listapp = from c in xdoc.Descendants("Ungdung") select c;
foreach (XElement app in listapp)
{
var xElement = app.Element("Name");
if (xElement != null)
progressIndicator.Text = "Checking " + xElement.Value + "...";
var element = app.Element("Id");
if (element != null)
{
var appId = element.Value;
var appVersion = await GetAppsVersion(appId);
app.Element("Version").Value = appVersion.ToString();
}
}
xdoc.Save(stream);
}
How can I solve this problem ?
Looks like you're appending modified document at the end of current file content. That's why you can't parse it later again.
I would split read and write parts into different using statements:
XDocument xdoc;
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Open, FileAccess.Read))
{
xdoc = XDocument.Load(stream, LoadOptions.None);
}
var listapp = from c in xdoc.Descendants("Ungdung") select c;
foreach (XElement app in listapp)
{
var xElement = app.Element("Name");
if (xElement != null)
progressIndicator.Text = "Checking " + xElement.Value + "...";
var element = app.Element("Id");
if (element != null)
{
var appId = element.Value;
var appVersion = await GetAppsVersion(appId);
app.Element("Version").Value = appVersion.ToString();
}
}
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Truncate, FileAccess.Write))
{
xdoc.Save(stream);
}
Setting FileMode.Truncate on second using statement will clear previous file content, what should fix your problem.

Unable to set content in SdtElement using WordprocessingDocument

I have a template file in which I have placed two place holders. Both are Plain Text Content Controls. I have following code in which I am setting the values to the Place Holders in the file.
static void Main(string[] args)
{
string fileName = "C:\\xxx\\Template.docx";
byte[] fileContent = File.ReadAllBytes(fileName);
using (MemoryStream memStream = new MemoryStream())
{
memStream.Write(fileContent, 0, (int)fileContent.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStream,true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
var sdtElements = wordDoc.MainDocumentPart.Document.Descendants<SdtElement>();
foreach (SdtElement sdtElement in sdtElements)
{
Tag blockTag = sdtElement.SdtProperties.Descendants<Tag>().ElementAt(0);
Run nr = new Run();
Text txt = new Text();
txt.Text = "RKS";
nr.Append(txt);
Lock lckContent = new Lock();
bool lockControl = true;
if (lockControl)
{
lckContent.Val = LockingValues.SdtContentLocked;
}
else
{
lckContent.Val = LockingValues.Unlocked;
}
if (sdtElement is SdtBlock)
{
(((SdtBlock)sdtElement).SdtContentBlock.ElementAt(0)).RemoveAllChildren();
(((SdtBlock)sdtElement).SdtContentBlock.ElementAt(0)).AppendChild<Run>(nr);
((SdtBlock)sdtElement).SdtProperties.Append(lckContent);
}
if (sdtElement is SdtCell)
{
((SdtCell)sdtElement).SdtContentCell.ElementAt(0).Descendants<Paragraph>().ElementAt(0).RemoveAllChildren(); ((SdtCell)sdtElement).SdtContentCell.ElementAt(0).Descendants<Paragraph>().ElementAt(0).AppendChild<Run>(nr);
((SdtCell)sdtElement).SdtProperties.Append(lckContent);
}
if (sdtElement is SdtRun)
{
//SdtContentText text = sdtElement.SdtProperties.Elements<SdtContentText>().FirstOrDefault();
//((SdtRun)sdtElement).SdtContentRun.ElementAt(0).AppendChild<Text>(emptyTxt);
((SdtRun)sdtElement).SdtContentRun.ElementAt(0).RemoveAllChildren();
((SdtRun)sdtElement).SdtContentRun.ElementAt(0).AppendChild<Run>(nr);
((SdtRun)sdtElement).SdtProperties.Append(lckContent);
}
}
wordDoc.MainDocumentPart.Document.Save();
}
}
}
The code runs successfully but the changes are not reflected in the file.
What am I missing?
You are creating a WordprocessingDocument from a memory stream, so there is no way for the class to know which file to write to. It writes all changes to the memory stream, not the file.
You can create a WordprocessingDocument directly from a file by calling WordprocessingDocument.Open method and specifying the name of your file (see https://msdn.microsoft.com/en-us/library/office/documentformat.openxml.packaging.wordprocessingdocument.aspx) and then the changes should be reflected in the file.
If you need to load the document into a buffer for some reason, then you need to copy the data from the buffer back to the file manually.
After making some experiments, I could not understand how it worked but it is fine for me. I just save the file with other name.
After the code line: wordDoc.MainDocumentPart.Document.Save(); I added
File.WriteAllBytes("C:\\xxx\\Sample.docx", memStream.ToArray());

Writing textbox values to xml file in C#.net

I have two TextBoxes namely txtUserid and txtPassowrd.
I'm writing the values entered in textboxes to a XML file but I do not want the same txtuserid values to be written twice in XML - it should be overwritten.
For example :
If I enter in txtUserid=2 and txtPassword=I
and the second time if I enter txtUserid=2 and txtPassword=m
then I only want one entry to be kept in the XML file :
For the above example: the txtUserid=2 and textPassword=m
The code:
XDocument Xdoc = new XDocument(new XElement("Users"));
if (System.IO.File.Exists("D:\\Users.xml"))
{
Xdoc = XDocument.Load("D:\\Users.xml");
}
else
{
Xdoc = new XDocument();
}
XElement xml = new XElement("Users",
new XElement("User",
new XAttribute("UserId", txtUserName.Text),
new XAttribute("Password", txtPassword.Text)));
if (Xdoc.Descendants().Count() > 0)
{
Xdoc.Descendants().First().Add(xml);
}
else
{
Xdoc.Add(xml);
}
Xdoc.Save("D:\\Users.xml");
Search your existing XML document for a node where the UserId attribute matches your current one, and if it does, modify that one, else make a new one.
I'd imagine that your coude would resemble the following:
List<XElement> list = Xdoc.Descendants("User").Where(el => el.Attribute("UserId").Value == txtUserName.Text).ToList();
if (list.Count == 0)
{
// Add new node
}
else
{
// Modify the existing node
}
Edit: In response to your comment, the code to edit your XElement would look something like
string myValue = "myValue";
list.First().Attribute("ElementName").SetValue(myValue);
Writing textbox values to XML file in C#
protected void btnSave_Click(object sender, EventArgs e)
{
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;
// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("Userid", Server.HtmlEncode(textUserid.Text));
myXmlElement.SetAttribute("Username", Server.HtmlEncode(textUsername.Text));
myXmlElement.SetAttribute("AccountNo", Server.HtmlEncode(txtAccountNo.Text));
myXmlElement.SetAttribute("BillAmount", Server.HtmlEncode(txtBillAmount.Text));
// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
myXmlDocument.Save(Server.MapPath("InsertData.xml"));
// Re-bind data since the doc has been added to
BindData();
Response.Write(#"<script language='javascript'>alert('Record inserted Successfully Inside the XML File....')</script>");
textUserid.Text = "";
textUsername.Text = "";
txtAccountNo.Text = "";
txtBillAmount.Text = "";
}
void BindData()
{
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
myXmlReader.Close();
}

Categories