There is an error in XML document (0, 0) during deserialization - c#

i have the following code to for xml serialization.
public class FormSaving
{
private string major;
public string Majorversion
{
get;
set;
}
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = #"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
FormSaving abc = new FormSaving();
abc.Majorversion = MajorversionresultLabel.Content.ToString();
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);
}
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
Stream checkStream = null;
Microsoft.Win32.OpenFileDialog DialogLoad = new Microsoft.Win32.OpenFileDialog();
DialogLoad.Multiselect = false;
DialogLoad.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
if ((bool)DialogLoad.ShowDialog())
{
try
{
if ((checkStream = DialogLoad.OpenFile()) != null)
{
loadpath = DialogLoad.FileName;
checkStream.Close();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
{
System.Windows.MessageBox.Show("Problem occured, try again later");
}
FormSaving abc;
using (Stream loadstream = new FileStream(loadpath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
abc = (FormSaving)serializer.Deserialize(loadstream);
}
MajorversionresultLabel.Content = abc.Majorversion;
}
When i press the SaveButton, my label.content is saved into an xml file. However when i press the load button to load this xml file, i get the error "There is an error in XML document (0, 0)". I went to open my xml file after pressing the load button, it becomes blank and everything got erased. Can anyone help me fix this load button error?

ok solved,
using (Stream loadstream = new FileStream(loadpath, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
abc = (FormSaving)serializer.Deserialize(loadstream);
}
should have been FileMode.Open instead of FileMode.Create

Related

Only ask for filename if one has not been input

I am using C# and a winform and am saving data to a .xlsx on a button click event. I have a unique situation that I am not sure how to code for....
If the form is still displayed and the user clicks the button, I want it to prompt for a file name and save location. BUT if the form has not been closed and the user clicks the button a second time, I want .xlsx to be saved in the same location and with the same filename and over write with no prompt.
This is the syntax I use to prompt for save name and location, but how do I check to determine if a filename/save location has already been input and if it has do not prompt again?
private void btnOne_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { Messagebox.Show("An error has occured"; }
}
}
So, whether the data has a set filename is a part of the state of the class. Inside the class where you have btnOne_Click, just define a string with the filename, defaulted to null:
string filepath = null;
Then, in your btnOne_Click, you want to check for the filepath. If it's not there, open the saveAs dialog. After that, if filepath is set, just save. It will be restructured like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (filepath == null)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK) {
filepath = save.FileName;
}
}
if (filepath != null)
{
try
{
var file = new FileInfo(filepath);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"; }
}
}
This logical structure gives you standard behavior for when a user presses a save button. If they cancel the saveAs dialog, then the save is aborted and the filename state is not changed.
Declare this globally:
public string Filename;
Then change your subroutine like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(Filename))
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
Filename = save.FileName;
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"); }
}
}
else
{
var file = new FileInfo(Filename);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
}

Wpf Listview exception Process is used by some other process

i am loading Mp3 Files from folder in Listview. right click option pn listview there is a option of Update tags.when i enter fields data and click update tags it throws ecception Process cant access file it is used by some other process here is my code
private void UpdateTagEditor_RegisterActionEventHandler(object sender, RoutedEventArgs e)
{
var tags = sender as UpdateTags;
string path = tags.targetPath;
string comments = tags.txtTagComment.Text;
string lyrics = tags.txtTagLyrics.Text;
try
{
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File tagFile = TagLib.File.Create(path);
tagFile.Tag.Comment = comments;
tagFile.Tag.Lyrics = lyrics;
tagFile.Save();
}
}
catch (Exception exception)
{
}
}
What are you using the Stream for? Nothing it seems. You are trying to create the file twice. Try to remove the stream:
private void UpdateTagEditor_RegisterActionEventHandler(object sender, RoutedEventArgs e)
{
var tags = sender as UpdateTags;
string path = tags.targetPath;
string comments = tags.txtTagComment.Text;
string lyrics = tags.txtTagLyrics.Text;
try
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File tagFile = TagLib.File.Create(path);
tagFile.Tag.Comment = comments;
tagFile.Tag.Lyrics = lyrics;
tagFile.Save();
}
catch (Exception exception)
{
}
}

Xml Serializing and Writer

in one class I create with a button click a XML document:
private void buttonCreate_Click(object sender, RoutedEventArgs e)
{
DialogResult result = folderElg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
textBoxPath.Text = folderElg.SelectedPath;
userConfigurePath = folderElg.SelectedPath;
}
XmlDocument toolConfig = new XmlDocument();
XmlNode myRoot;
myRoot = toolConfig.CreateElement("Tool");
toolConfig.AppendChild(myRoot);
toolConfig.Save(#userConfigurePath + "\\config.xml");}
There I haven't problems. The folder is created and the xml file also.
So in an other class I want to serialize objects into the xml file 'config.xml' (The variable userConfigurePath is static in the classe mentionned above):
public partial class MainWindow : Window
{
private string inputNewTool = "";
private OpenFileDialog dlg = new OpenFileDialog();
public MainWindow()
{
InitializeComponent();
}
private void buttonAdd_Click(object sender, RoutedEventArgs e)
{
InputDialog input = new InputDialog();
input.ShowDialog();
inputNewTool = input.enteredTxt;
if (inputNewTool != null)
{
System.Windows.Forms.MessageBox.Show("Chose the Tool's directory");
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Tool tool = new Tool();
tool.Name = inputNewTool;
tool.Path = dlg.FileName;
XmlSerializer serializer = new XmlSerializer(tool.GetType());
StreamWriter writer = new StreamWriter(#Start.userConfigurePath +
"\\config.xml");
serializer.Serialize(writer.BaseStream, tool);
}
}
The result is that the object isn't saved in the config.xml file. Why?
Edit the Tool's Class:
public class Tool
{
public string Name { get; set; }
public string Path { get; set; }
public Tool() { }
}
Second Edit:
I see that i can't delete manuel these folder (after the application is closed) with the xml file when it is created. Why?
Third Edit:
I changed my Code so:
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Tool tool = new Tool();
tool.Name = inputNewTool;
tool.Path = dlg.FileName;
XmlSerializer serializer = new XmlSerializer(tool.GetType());
using (var writer = new StreamWriter(#Start.userConfigurePath +
"\\config.xml"))
{
serializer.Serialize(writer.BaseStream, tool);
writer.Close();
}
Now the first object is serialized. But if i create another tool in the same way the config.xml doesn't take it. Only the first tool is serialized:
<?xml version="1.0"?>
<Tool xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>dffss</Name>
<Path>D:\Users\xxxx\Documents\schulewochenbericht.txt</Path>
</Tool>
You need to close the StreamWriter object to flush the data into the file. Please try the following:
XmlSerializer serializer = new XmlSerializer(tool.GetType());
using (var writer = new StreamWriter(#Start.userConfigurePath + "\\config.xml"))
{
serializer.Serialize(writer.BaseStream, tool);
}
In addition to the answer from wdosanjos, you should also realize that you can't just write a sequence of Tool objects. If you want to write more than one Tool, then you need to write an array or list of Tool.

Can not upload file from C# (WPF) FTP

i have created a small ftp program in c# using winforms but when i try to create this in wpf it is showing me an error "Value cannot be null. Parameter name:fileName", The code works fine in winform.
here is the code:
public partial class Ftp : UserControl
{
string filePath;
public Ftp()
{
InitializeComponent();
}
//Clear TextBox when clicked
#region textBox clear
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
//TextBox tb = (TextBox)sender;
//tb.Text = string.Empty;
//tb.GotFocus -= TextBox_GotFocus;
}
#endregion
//Open File Dialog
private void browser_click(object sender, RoutedEventArgs e)
{
#region File Dialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.CheckFileExists = true;
dlg.DefaultExt = ".txt";
dlg.Filter = "JPEG Files (*.txt)|*.txt|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
dlg.FileName = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Open document
string filename = dlg.FileName;
pathtext.Text = filename;
}
#endregion
}
//Upload the File to FTP
private void Upload_click(object sender, RoutedEventArgs e)
{
#region Upload files
if (filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
browser.IsEnabled = false;
try
{
FileInfo fileInfo = new FileInfo(filePath);
string fileName = fileInfo.Name.ToString();
WebRequest requestFTP = WebRequest.Create("ftp://" + hosttext.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(usertext.Text, passtext.Password);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
MessageBox.Show("File Uploading Is SuccessFull...");
}
catch (Exception ep)
{
MessageBox.Show("ERROR: " + ep.Message.ToString());
}
browser.IsEnabled = true;
filePath = "";
hosttext.Text = usertext.Text = passtext.Password = pathtext.Text = "";
}
#endregion
}
}
You never set your filePath variable, so it's null. In browser_click you need to do something like
if (result == true)
{
// Open document
string filename = dlg.FileName;
filePath = filename; //added this line
pathtext.Text = filename;
}
Also, you think you have handled your invalid string here:
if (filePath == "")
but at that point filePath = null.
Instead, use if (string.IsEmptyOrNull(filePath))

empty path name not legal

I have a "save" button so when users click, it will do a saving of xml file(xml serialization). A savefiledialog is used here and when i press cancel without selecting any file an "Argument Exception" occurs and says "Empty path name is not legal". How do i handle this exception? I would like the form to remain the same even without any path selected in the savefiledialog. Many thanks.
My savefiledialog snippet:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = #"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
...
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
}
My argument exception occurs at this line:
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
The problem here is that you do not care about the result of the Save dialog, and you try to save even if the user clicked Cancel. You should change the code to look something like this instead:
...
DialogSave.InitialDirectory = #"C:/";
if( DialogSave.ShowDialog() == DialogResult.OK )
{
savepath = DialogSave.FileName;
DialogSave = null;
...
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
}
DialogSave.Dispose();
You probably don't want to save if the user cancels the dialog? Check for the result from ShowDialog and act accordingly:
if (DialogSave.ShowDialog() == true)
{
savepath = DialogSave.FileName;
...
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
}

Categories