SaveFileDialog existing file - c#

I am using the savefiledialog in C# and I am allowing the user to save an xml node to a file however if the user chooses to create a new file and save the node in it, it works but when the user chooses to save to an existing file then it is overwritten. what I need is that it kind of loads the file and I can append the node in it, Thanks
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.FileName = "untitled"; // Default file name
sfd.DefaultExt = ".xml"; // Default file extension
sfd.Filter = "Xml documents (.xml)|*.xml";
Nullable<bool> result = sfd.ShowDialog();
if (result == true)
{
if (System.IO.Path.GetExtension(sfd.FileName) != ".xml")
{
MessageBox.Show("You can only choose files with .xml extensions");
return;
}
this.save_xml_file(sfd.FileName);
}
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
doc.AppendChild(docNode);
XmlNode fubiRec = Doc.CreateElement("FubiRecognizers");
XmlAttribute conf = Doc.CreateAttribute("globalMinConfidence");
conf.Value = "0.51";
fubiRec.Attributes.Append(conf);
doc.AppendChild(fubiRec);
XmlAttribute gestureAttribute = doc.CreateAttribute("name");
gestureAttribute.Value = gestureName;
gestureNode.Attributes.Append(gestureAttribute);
fubiRec.AppendChild(gestureNode);

If you use FileStream and StreamWriter then you need to specify your type of Stream first.
FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write);
FileMode.Append will create file if it doesn't exist,and append the one that exists.
Then use it in StreamWriter
StreamWriter sw = new StreamWriter(fileSTream, Encoding.Default);
If you don't use this kind of stream or writer, there is always something similar available.

Related

How do I overwrite a file if it already exists?

I'm making a text editor using fastColoredTextbox. I have a button that allows you to save your text onto your pc. The problem is that it throws an exception when the user tries to save the file as a file that already exists, instead of overwriting the file.
This is my code.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
How would I go about making it overwrite the file if it already exists?
Maybe this could help you:
sw = new StreamWriter(path, true);
sw.WriteLine(line);
https://learn.microsoft.com/es-es/dotnet/api/system.io.streamwriter.-ctor?view=net-6.0#system-io-streamwriter-ctor(system-string-system-boolean)
I changed up my code a bit and ended up going with this, which somehow got it to work.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream s = saveFileDialog1.OpenFile();
StreamWriter sw = new StreamWriter(s);
sw.Write(fastColoredTextBox1.Text);
sw.Close();
}

How to add XML schema and XML element together in same file?

**
I want to add XML schema and XML element together in same file. Because this xml file we will need to generate through C# based on specific record. So, i am looking some code help how can i write together XMLSchema and XML element in same file and inside same element. Please check attachment.
<Survey>
**Here i want XML schema**
**Here i want XML element**
</Survey>
Working Code Example
SiteSurveyX siteSurveyX = new SiteSurveyX();
XmlTextReader reader = new XmlTextReader("c:\\temp\\TestSiteSchema.xsd");
//siteSurveyX.SurveySchema = XmlSchema.Read(reader, null);
XmlSchema myschema = XmlSchema.Read(reader, null);
string filePath = HelperFunctions.SurveyFilePath + routeName;
////Get all node record from DB
siteSurveyX.Survey = routeService.GetRouteDetailForXML(routeId, Convert.ToString(ddlRoute.Text), chkCurrentInterruption.Checked);
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
lblStatus.Text = "Preparing file";
stream.Close();
stream.Dispose();
//Convert record in XML
XmlSerializer serializer = new XmlSerializer(typeof(SiteSurveyX));
using (StreamWriter writer = new StreamWriter(filePath, true))
{
serializer.Serialize(writer, siteSurveyX);
lblStatus.Text = "Ready";
}
}
It's done with this code.

encrypting a copy of a text file in c# (Windows Forms)

I'm working on an encryption program in C# (Windows Forms) and one of the options I'd like to add is that the user will be able to choose an existing text (.txt) file, and the program would make a new file which is the file chosen, but encrypted (without making any changes in the original file).
I though about making a copy of the original file and then encrypting the new file, but I have no clue how to do it.
Please tell me how to do it.
Thanks a lot in advance!
StreamReader/StreamWriter for loading and saving the file.
StreamReader:
string unencryptedText;
private void ReadTextFile()
{
using (StreamReader reader = new StreamReader("file.txt"))
{
unencryptedText= reader.ReadToEnd();
}
}
StreamWriter
using (StreamWriter writer = new StreamWriter("encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
Encryption: Simple insecure two-way "obfuscation" for C#
Update
Chose Directory where to save encrypted file(only Directory)
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(fbd.SelectedPath+"\\encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
}
Chose Directory and FileName
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(sfd.FileName, true))
{
writer.Write(encryptedText);
}
}
Use System.IO.StreamReader and System.IO.StreamWriter to read and write from text files.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
using (StreamReader sr = new StreamReader(filePath))
{
fileContents = sr.ReadToEnd();
}
string encryptedContents = Encrypt(fileContents);
using (StreamWriter sw = new StreamWriter(destinationPath))
{
sw.Write(encryptedContents);
}
File.Copy(pathX,pathY)
Will copy the file from path X to path Y.
The next thing is to write the encrypted text to the copied file:
File.WriteAllText(pathY,textToWrite)
I can also say you will learn more if you read msdn examples.
Everything you look for is there.

Packagepart copy to file or to memory

I want to extract a xlsx file to get the sheet1.xml file. Now I am struggling with the package and PackagePart. I think the most obvious way is to read that particular file and copy the content to the XmlDocument
This is what i have this far:
XmlDocument doc = new XmlDocument();
using (Package package = ZipPackage.Open(xlsFile, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in package.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
{
FileStream targetFile = File.OpenWrite(target);
byte[] bytes = new byte[source.Length];
source.Read(bytes, 0, (int)source.Length);
source.Close();
//source.CopyTo(targetFile);
//doc.Load(source.Write());
//targetFile.Close();
}
}
}
I am using .net 3,5 so I cannot use the Stream source.CopyTo methods.
I would like to copy the contents of the Sheet1.xml to the doc of the XmlDocument class..
Thanks!
Paul
You can use XmlDocument.Load overload which takes a Stream:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
Once loaded, you then can use XmlDocument.Save:
xmlDoc.Save(target);

I want to edit my xml file

Hi I am working on XML file, here I want to give rights to user to edit my xml file nodes to his own custom language.
I am enclosing my code, but it is not editting my xml file. Need assistance.
class Program
{
static void Main(string[] args)
{
//The Path to the xml file
string path = "D://Documents and Settings//Umaid//My Documents//Visual Studio 2008//Projects//EditXML//EditXML//testing.xml";
//Create FileStream fs
System.IO.FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Create new XmlDocument
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
//Load the contents of the filestream into the XmlDocument (xmldoc)
xmldoc.Load(fs);
//close the fs filestream
fs.Close();
//Change the contents of the attribute
xmldoc.DocumentElement.ChildNodes[0].Attributes[0].InnerText = "Umaid";
// Create the filestream for saving
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
// Save the xmldocument
xmldoc.Save(WRITER);
//Close the writer filestream
WRITER.Close();
}
}
My XML file which I am going to edit, but couldn't.
<?xml version="1.0" encoding="utf-8" ?>
<rule id="city" scope="public">
<one-of>
<item>Boston</item>
</one-of>
</rule>
What do you really want to do with your XML?? Which attribute to you want to change??
One hint: you can load and save XmlDocument to a path directly - no need for the filestream .....
xmldoc.Load(#"D:\yourpath\file.xml");
xmldoc.Save(#"D:\yourpath\newfile.xml");
The problem is that your expression xmldoc.DocumentElement.ChildNodes[0] selects the <one-of> node which has no attributes.
You cannot change a non-existing attribute.
If you want to change the "id" attribute of <rule>, you need to do this on the DocumentElement:
xmldoc.DocumentElement.Attributes["id"].Value = "Umaid";
If you want to change the text inside the <item>, do this:
XmlNode itemNode = xmldoc.SelectSingleNode("/rule/one-of/item");
if(itemNode != null)
{
itemNode.InnerText = "Umaid";
}
Marc
class Program
{
static void Main(string[] args)
{
string path = "D:\\Documents and Settings\\Umaid\\My Documents\\Visual Studio 2008\\Projects\\EditXML\\EditXML\\testing.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
var itemNode = doc.SelectSingleNode("rule/one-of/item");
if (itemNode != null)
{
itemNode.InnerText = "Umaid";
}
doc.Save(path);
}
}

Categories