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)
{
}
}
Related
I am creating a program that creates, writes, and saves an xml file. When I try to open the saved file I get an error that says the file cannot be accessed because it is being used by another process. I assumed it was because I didn't close the filestream after I saved the file so I made the correction. I still can't open the file and I receive the same error. I'm not sure what the issue is beyond this point. How can I fix this?
namespace XML_DataSets
{
public partial class FormAddNew : Form
{
XmlSerializer xs;
List<Class1> ls;
//create the DataTable
DataTable dt = new DataTable("Contact");
XDocument xd = new XDocument();
public FormAddNew()
{
InitializeComponent();
ls = new List<Class1>();
xs = new XmlSerializer(typeof(List<Class1>));
//create columns for the DataTable
DataColumn dc1 = new DataColumn("Id");
dc1.DataType = System.Type.GetType("System.Int32");
dc1.AutoIncrement = true;
dc1.AutoIncrementSeed = 1;
dc1.AutoIncrementStep = 1;
//add columns to the DataTable
dt.Columns.Add(dc1);
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Age"));
dt.Columns.Add(new DataColumn("Gender"));
//create DataSet
DataSet ds = new DataSet();
ds.DataSetName = "AddressBook";
ds.Tables.Add(dt);
}
private void buttonCreate_Click(object sender, EventArgs e)
{
DataRow row = dt.NewRow();
row["Name"] = textBoxName.Text;
row["Age"] = textBoxAge.Text;
row["Gender"] = textBoxGender.Text;
dt.Rows.Add(row);
dataGridView1.DataSource = dt;
//dt.WriteXml("Contacts.xml");
xd = WriteDt2Xml(dt);
}
public static XDocument WriteDt2Xml(DataTable dt)
{
using (var stream = new MemoryStream())
{
dt.WriteXml(stream);
stream.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader = XmlReader.Create(stream, settings);
reader.MoveToContent();
if (reader.IsEmptyElement) { reader.Read(); return null; }
return XDocument.Load(reader);
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream input = null;
OpenFileDialog dialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((input = openFileDialog.OpenFile()) != null)
{
FileStream fs = new FileStream(#openFileDialog.FileName.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
ls = (List<Class1>)xs.Deserialize(fs);
dataGridView1.DataSource = ls;
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR");
}
}
}
}
}
#Daniel Advise taken well...I refactored the code and see the error you referred to. I checked out the two links you provided as examples. I made corrections but I still get the same result.
First change the way you open the file to:
using (var fs = new FileStream(#openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
ls = (List<Class1>) xs.Deserialize(fs);
dataGridView1.DataSource = ls;
}
an then try to check (Debug) the entire Exception in openToolStripMenuItem_Click event:
System.InvalidOperationException was caught
HResult=-2146233079
Message=There is an error in XML document (2, 2).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at WindowsFormsApplication1.FormAddNew.openToolStripMenuItem_Click(Object sender, EventArgs e) in c:\Users\admin\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\FormAddNew.cs:line 131
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=<AddressBook xmlns=''> was not expected. --The problem!
Source=Microsoft.GeneratedCode
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfClass1()
InnerException:
Then read:
xmlns='' was not expected when deserializing nested classes
{"<user xmlns=''> was not expected.} Deserializing Twitter XML
Update:
You need an atomic object when desalinizing like:
public class AddressBook
{
public AddressBook()
{
Contacts = new List<Contact>();
}
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
and I would suggest to get rid of xDocument, DataSet & DataTable. they add too much complication for nothing. and I guess the reason u r using them because of DataGrid which is minor concern, focus on coding first:
private readonly XmlSerializer xs;
private AddressBook ls;
private int _counter = 0;
public FormAddNew2()
{
InitializeComponent();
ls = new AddressBook();
xs = new XmlSerializer(typeof(AddressBook));
}
private void buttonCreate_Click(object sender, EventArgs e)
{
var addressBookContact2 = new Contact
{
Id = ++_counter,
Name = textBoxName.Text,
Age = textBoxAge.Text,
Gender = textBoxGender.Text
};
ls.Contacts.Add(addressBookContact2);
dataGridView1.DataSource = null; // strangly u need this
dataGridView1.DataSource = ls.Contacts;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Select save location file name";
saveFileDialog.Filter = "XML-File | *.xml";
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
using(var writer = new StreamWriter(saveFileDialog.FileName))
{
xs.Serialize(writer, ls);
MessageBox.Show(saveFileDialog.FileName);
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var reader = new StreamReader(#openFileDialog.FileName))
{
ls = (AddressBook) xs.Deserialize(reader);
_counter = 0;
dataGridView1.DataSource = ls.Contacts;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "ERROR");
}
}
}
I have been trying to upload images via a file upload control. The file is not being uploaded and I keep getting the following error:"Cannot access a closed file."
I am unsure as to why I am getting this error, any assistance would be appreciated.
My code: First is the code that grabs the image and creates the 'preview'
protected void btnupload_Click(Object sender, EventArgs e)
{
Session["Image"] = flupGalImg.PostedFile;
Stream fs = flupGalImg.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgGalImg.ImageUrl = "data:image/png;base64," + base64String;
imgGalImg.Visible = true;
}
My code that calls my business logic code:
else if(btnaddedit.Text == "Add item")
{
if(txtItemTitle.Text != "")
{
if(txtItemDescription.Text != "")
{
if(Session["Image"] != null)
{
HttpPostedFile postedFile = (HttpPostedFile)Session["Image"];
int alb;
int.TryParse(hdnAlbId.Value, out alb);
if(newsLogic.CreateNewGalleryItem(txtItemTitle.Text, txtItemDescription.Text, alb, postedFile) == true)
{
// Do something.
}
}
}
}
}
And finally my business logic code:
// create gallery item
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
public bool CreateNewGalleryItem(string itemTitle, string itemDescription, int itemAlbum, HttpPostedFile itemFile)
{
string folderpath = #"~/Images/GalleryImages/";
string filename = Path.GetFileName(itemFile.FileName.ToString());
bool itemCreated = false;
string itemImgPath;
try
{
itemImgPath = Path.Combine(folderpath + filename);
string itemImgUploadPath = Path.Combine(HttpContext.Current.Server.MapPath(folderpath) + filename);
itemFile.SaveAs(itemImgUploadPath);
galAdp.CreateGalleryItem(itemTitle, itemDescription, itemImgPath, itemAlbum);
itemCreated = true;
}
catch (Exception er)
{
itemCreated = false;
string consmsg = er.Message;
}
return itemCreated;
}
My 'image preview' works just fine. The error is thrown on this line of the business logic: itemFile.SaveAs(itemImgUploadPath);
When I did a google search (well lots of google searches) I read that it may be the file size so I increased the max allowed content in the web.config but nothing changed.
Any ideas as to what I am doing wrong?
My project stores phone numbers into a list<> and saves them into a .bin file:
private void savebutton_Click(object sender, EventArgs e)
{
SaveFileDialog sv = new SaveFileDialog();
sv.Filter = "Binary files (*.bin)|*.bin|All files(*.*)|*.*";
sv.Title = "Save File";
sv.FilterIndex = 2;
sv.RestoreDirectory = true;
sv.InitialDirectory = Path.GetFullPath(#"F:\Computer Technology Skills\Programming 35\Module 1\ICA10\ICA10\bin\Debug");
if (sv.ShowDialog() == DialogResult.OK)
{
try
{
FileStream fs = new FileStream(sv.FileName, FileMode.Create, FileAccess.Write);
BinaryWriter file = new BinaryWriter(fs);
// System.IO.StreamWriter file = new System.IO.StreamWriter(sv.FileName.ToString());
var message = string.Join(Environment.NewLine, PhoneNum);
file.Write(message);
file.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Then pressing the load button is supposed to delete the items currently in the listbox1 to replace them with whatever items were in the bin file on each line.
private void loadbutton_Click(object sender, EventArgs e)
{
OpenFileDialog od = new OpenFileDialog();
string databyte = null;
long iNumInts = 0;
od.RestoreDirectory = true;
od.InitialDirectory = Path.GetFullPath(#"F:\Computer Technology Skills\Programming 35\Module 1\ICA10\ICA10\bin\Debug");
if (od.ShowDialog() == DialogResult.OK)
{
try
{
FileStream fs = new FileStream(od.FileName, FileMode.Open);
listBox1.Items.Clear();
using (BinaryReader reader = new BinaryReader(fs))
{
iNumInts = fs.Length / sizeof(int);
for (int i = 0; i < iNumInts; i++)
{
databyte = reader.ReadString(); //Endofstreamexception
listBox1.Items.Add(databyte);
}
fs.Close();
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The problem is, when I load the file I saved, the items are all stuck on the first index of the listbox1 and I receive an endofstream exception.
I'm a bit confused here since my notes didn't help much and other stack overflow questions I found were examples using integers or arrays. I switched from streamwriter to binarywriter which helped a lot, but any help would be much appreciated!
I would recommend using the StreamReader for this.
using (StreamReader reader = new StreamReader(od.Filename))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
listbox1.Items.Add(line);
}
}
You can also use File.ReadLines which does it all for you (if you're using .NET 4 or above).
Looking at your save code, it looks like you are writing the phone numbers as a single string with a newline delimiter between them. In the read code you are trying to read them as individual strings with the ReadString method.
One string out equals one string in. In other words, if you write them all out as one string, then read them all in as one string. Then you could use string.split and get the individual numbers.
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))
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