I have an xml file which contain images url . i am verifying the url whether url is responsive or not. If url is not responsive then i am removing that url from xml. and saving all changes . but i am getting error like
'The process cannot access the file 'E:\1.xml' because it is being used by another process'
xmlTR = new XmlTextReader(#"E:\1.xml");
PrimaryXmlDoc.Load(xmlTR);
foreach (XmlNode node in PrimaryXmlDoc.SelectNodes("/fp-hotel/Images/Url"))
{
if (CheckUrlExists(node.InnerText))
{
}
else
{
XmlElement _xmlElement = PrimaryXmlDoc.DocumentElement;
node.ParentNode.RemoveChild(node);
}
}
PrimaryXmlDoc.Save(#"E:\1.xml");
I assume that you have to Close XmlTextReader before using it second time. If you don't do that, the previous instance will keep your file open and you won't be able to open it again.
EDIT: And that's what happens here is probably that you want to save file before closing it.
Add line:
xmlTR.Close();
before
PrimaryXmlDoc.Save(#"E:\1.xml");
Related
I am trying to read a text file and display it on plage. This is what I did. But I am getting error
The process cannot access the file
'D:\wwwroot\TestProject\Logs\TestLog.log' because it is being used by
another process.
Controller Code
Array LogFileData = null;
var logFileNameWithPath = Server.MapPath("D:\wwwroot\TestProject\Logs\TestLog.log");
if (System.IO.File.Exists(logFileNameWithPath))
{
LogFileData = System.IO.File.ReadAllLines(logFileNameWithPath);
}
ViewBag.logFileContent = LogFileData;
View Code
#if (ViewBag.logFileContent != null)
{
foreach (string dataLine in ViewBag.logFileContent)
{
#dataLine
<br />
}
}
The log file is created and used by a service. My code works when I stop service. But I am not trying to write to file exclusively at the same time service is writing to it. Infact I am trying to read at a time when service is not writing to it. Any advice on how can I fix this? THanks.
Generally, you need to specify the "access mode" when you try to read the file. Please take a look here. Try to open the file into a FileStream with appropriate access.
I will post some code when I can.
I have a problem saving my xml-file.
i use this XMLwriter :
using (XmlWriter writer = XmlWriter.Create("CarsXML.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("CarsXml");
foreach (Car item in cars)
{
writer.WriteStartElement("Car");
writer.WriteElementString("Brand", item.Brand);
writer.WriteElementString("Type", item.Type);
writer.WriteElementString("Price", item.Price);
writer.WriteElementString("Effect", item.Effect);
writer.WriteElementString("Year", item.year);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
Seems ok right? No compile errors..
I´ve also tried this just for testing :
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
Still no luck.. `ve trid this in a console app, and it works so the code must be fine..
I´ve also tried with a piece of code i found somewhere - using XmlDocument instead - but its the same deal.
What am i doing wrong?
When you are in a web application, the current directory is not the root directory of the web application. It's the directory where the IIS executable is, so that's somewhere in the Windows system directories.
Naturally you don't have write access to that directory from the web application, so you get some exception when you try to create a file there.
Specify the full path of the file that you want to create. You can use the MapPath method to get the physical path to a file from a virtual path. Example:
string fileName = Server.MapPath("/xmldata/CarsXML.xml");
using (XmlWriter writer = XmlWriter.Create(fileName))
...
I am trying to read an Excel sheet using C# which is to be loaded by end user from fileUpload control.
I am writing my code to save the file on server in event handler of another button control(Upload). But when I click on Upload Button I am getting this exception:
The process cannot access the file 'E:\MyProjectName\App_Data\sampledata.xlsx' because it is being used by another process.
Here is the code that I have used in event handler:
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
Even deleting the file is not working, throwing the same exception.
Make sure, some other process is not accessing that file.
This error might occurs whenever you are trying to upload file, without explicitly removing it from memory.
So try this:
try
{
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
}
catch (Exception ex)
{
throw ex.Message;
}
finally
{
file_upload.PostedFile.InputStream.Flush();
file_upload.PostedFile.InputStream.Close();
file_upload.FileContent.Dispose();
//Release File from Memory after uploading
}
The references are hanging in memory, If you are using Visual Studio try with Clean Solution and Rebuild again, if you are in IIS, just do a recycle of your application.
To avoid this problems try to dispose the files once you used them, something like:
using(var file= new FileInfo(path))
{
//use the file
//it will be automatically disposed after use
}
If i have understood the scenario properly.
For Upload control, I don't think you have to write code for Upload Button. When you click on your button,your upload control has locked the file and using it so it is already used by one process. Code written for button will be another process.
Prior to this, check whether your file is not opened anywhere and pending for edit.
i am using file upload control in server side when iam trying to get the file it is showing no file present
<asp:FileUpload ID="upldDocument" runat="server" />
string fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
if (upldDocument.HasFile)
{
}
i am getting a empty string as file extension and upldDocument.HasFile is returning false even after selecting a file.
what could be the reason??
Based on the posted code, I can only offer a best guess. There's not enough code posted to be sure what the problem is, but here's my best guess:
If you're not already, you need to check the HasFile property.
See here for a full example:
Edit - added
Using HasFile AFTER the bad code won't help. You need to put the code to get the extention inside an if statement so that it only attempts to read the extension if there IS a file.
string fileExtension = "";
if (upldDocument.HasFile)
{
fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
}
else
{
//No file selected by user, which is why you can't get the extension.
// handle this eventuality here even if it means just returning from the function and not doing anything.
}
How are you checking the values? (in what event)
Did you set the enctype attribute of the form to "multipart/form-data" ?
How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.