file cannot be deleted used by another process - asp.net

when ever i try to delete this files some times i get this message
file cannot be deleted used by another process
even though file is not used by any other user
the code what i am using
try
{
FileInfo TheFile = new FileInfo(MapPath(".") + "\\" + txtFile.Text);
if (TheFile.Exists) {
File.Delete(MapPath(".") + "\\" + txtFile.Text);
}
else {
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex) {
lblStatus.Text += ex.Message;
}
is there way we can assign a boolean value
here if true means i can display an message tellingfile is deleted successfully
boolean value is false
here if false means i can display an message telling file used by another process
can i write that condition here
File.Delete(MapPath(".") + "\\" + txtFile.Text);
any help would be great thank you

Based on my experience, if it says the file is being used by another process, the file is being used by another process, whatever you think...
Download ProcessExplorer to find out who the culprit is...

You can use the
FileInfo.Delete
method. If the file does not exist, this method does nothing.
Note
Also check for any other file handles that has locked this file, close them before deleting the file.

A bit late to the party I know, but hopefully these comments will help others out ->
The issue is not happening in Chrome, but is in IE6/7/8 and FF. This method is working for me now in those latter browsers:
try
{
System.IO.File.Delete(basePath + assetImage.Path);
}
catch
{
System.IO.File.Move(basePath + assetImage.Path, basePath + #"DELETE\ " + assetImage.Path);
}

Why don't you try
if (TheFile.Exists) {
TheFile.Delete();
}
?

If the Indexing Service is turned on, make sure this folder is excluded from the Index list.

If you want a method which just returns true if the file was deleted successfully, and false otherwise, I'd go with:
public bool DeleteFile(string fullPath) {
bool fileDeleted = false;
if (System.IO.File.Exists(fullPath))
{
try
{
System.IO.File.Delete(fullPath);
fileDeleted = true;
}
catch (UnauthorizedAccessException)
{
// File is open **or read only**
}
}
else
{
// File does not exist
}
return fileDeleted;
}

Related

How to try catch block in Jmeter.Webdriver webdriver Sampler

I want to do the exception handling in Jmeter.Webdriver Webdriver Sampler
Please let me , How to use try/catch block in Jmeter.Webdriver webdriver Sampler ?
You can do this via normal JavaScript try block, here is an example of taking a screenshot when error occurs:
var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
var wait = new support_ui.WebDriverWait(WDS.browser, 5)
var exception = null
WDS.sampleResult.sampleStart()
try {
WDS.browser.get('http://example.com')
wait.until(conditions.presenceOfElementLocated(pkg.By.linkText('Not existing link')))
} catch (err) {
WDS.log.error(err.message)
var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
screenshot.renameTo(java.io.File('screenshot.png'))
exception = err
} finally {
throw (exception)
}
WDS.sampleResult.sampleEnd())
Don't forget to "throw" the error after you handle it otherwise it will be "swallowed" and you get a false positive result.
See The WebDriver Sampler: Your Top 10 Questions Answered article for more tips and tricks
Surround the code with try block and add catch block at the end by giving variable name to capture the exception. (in the example, it is exc)
try as follows:
try{
WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
var pkg = JavaImporter(org.openqa.selenium)
WDS.browser.findElement(pkg.By.id('what')) // there is no such element with id what
WDS.sampleResult.sampleEnd()
}
catch(exc){ //exc variable name
WDS.log.error("element not found" + exc)
}
in the JMeter log, you can see the complete trace of NoSuchElementException, which is raised when trying to find the element by id with the values as what, which is not present in the HTML.
Note: use View Results in Table to see the Sampler response time.
Reference:
https://jmeter-plugins.org/wiki/WebDriverSampler/
Reference Image:
It is same as how do you do in other IDEs like eclipse.
you can see below code
//try block starts here
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element"))).click();
}
catch(Exception e)
{
WDS.log.info("Exception is : " +e);//you can print the exception in jmeter log.
}
double quotes should be replaced with the single quote if you are using javascript Since the BeanShell is easy and it is similar to java use BeanShell as much as possible

Blackberry not creating a valid sqlite database

I have a very unusual problem.
I'm trying to create a simple database (6 tables, 4 of which only have 2 columns).
I'm using an in-house database library which I've used in a previous project, and it does work.
However with my current project there are occasional bugs. Basically the database isn't created correctly. It is added to the sdcard but when I access it I get a DatabaseException.
When I access the device from the desktop manager and try to open the database (with SQLite Database Browser v2.0b1) I get "File is not a SQLite 3 database".
UPDATE
I found that this happens when I delete the database manually off the sdcard.
Since there's no way to stop a user doing that, is there anything I can do to handle it?
CODE
public static boolean initialize()
{
boolean memory_card_available = ApplicationInterface.isSDCardIn();
String application_name = ApplicationInterface.getApplicationName();
if (memory_card_available == true)
{
file_path = "file:///SDCard/" + application_name + ".db";
}
else
{
file_path = "file:///store/" + application_name + ".db";
}
try
{
uri = URI.create(file_path);
FileClass.hideFile(file_path);
} catch (MalformedURIException mue)
{
}
return create(uri);
}
private static boolean create(URI db_file)
{
boolean response = false;
try
{
db = DatabaseFactory.create(db_file);
db.close();
response = true;
} catch (Exception e)
{
}
return response;
}
My only suggestion is keep a default database in your assets - if there is a problem with the one on the SD Card, attempt to recreate it by copying the default one.
Not a very good answer I expect.
Since it looks like your problem is that the user is deleting your database, just make sure to catch exceptions when you open it (or access it ... wherever you're getting the exception):
try {
URI uri = URI.create("file:///SDCard/Databases/database1.db");
sqliteDB = DatabaseFactory.open(myURI);
Statement st = sqliteDB.createStatement( "CREATE TABLE 'Employee' ( " +
"'Name' TEXT, " +
"'Age' INTEGER )" );
st.prepare();
st.execute();
} catch ( DatabaseException e ) {
System.out.println( e.getMessage() );
// TODO: decide if you want to create a new database here, or
// alert the user if the SDCard is not available
}
Note that even though it's probably unusual for a user to delete a private file that your app creates, it's perfectly normal for the SDCard to be unavailable because the device is connected to a PC via USB. So, you really should always be testing for this condition (file open error).
See this answer regarding checking for SDCard availability.
Also, read this about SQLite db storage locations, and make sure to review this answer by Michael Donohue about eMMC storage.
Update: SQLite Corruption
See this link describing the many ways SQLite databases can be corrupted. It definitely sounded to me like maybe the .db file was deleted, but not the journal / wal file. If that was it, you could try deleting database1* programmatically before you create database1.db. But, your comments seem to suggest that it was something else. Perhaps you could look into the file locking failure modes, too.
If you are desperate, you might try changing your code to use a different name (e.g. database2, database3) each time you create a new db, to make sure you're not getting artifacts from the previous db.

error in displaying data from specific XML tags in a file?

XmlTextReader reader = new XmlTextReader("D://project_elysian//data.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
reader.Read();
//Response.Write(reader.Value + "</br>");
//Response.Write(reader.Depth);
switch (reader.Name)
{
case "Id": Response.Write(reader.Value + "</br>");
break;
case "Name": Response.Write(reader.Value + "</br>");
break;
}
}
}
I am trying to read data.xml file and display its contents of the specified tags, but the resultant page remains blank, and no compilation error is given, am stuck, can't figure out what is wrong with this code.
I suspect if you "View Source" on the resulting page you'll see the data you are expecting to see.
The problem is that your web browser sees these xml elements as unknown html tags and so doesn't know how to display them.
You need to "encode" your output, so your string is literally displayed as is.
Instead of writing:
Response.Write(reader.Value + "</br>");
try
Response.Write(Server.HtmlEncode(reader.Value) + "</br>");
What this does is replace < with < > with > and a few others. "<" tells the browser to render "<" rather than treat it as the beginning of a tag.
[Edit - in response to comment]
It sounds like your none of your cases are ever true. Without knowing the contents of the source xml file, it is hard to say - but have you tried putting a breakpoint on the Response.Writes in the cases? Are they ever hit?
If not, then this is not related to anything I mentioned above - but you are not getting what you expect from your reader.
Try starting with a small sample of the xml file and step through in the debugger. Try and determine what data (e.g. the reader.Name property) is present on the reader when you hit something you are interested in, and amend the switch statement accordingly.
[2nd Edit - in response to sample xml]
Your mistake is the Read() call just after the check for the XmlNodeType.Element. You are basically reading until you find an element (the Read() call in the while). Once you've found the element, you are then pushing past the element (the other Read() call) before trying to read the element name. This inner reader.Read() makes sure you are no longer on the element by the time you try to check its name.
Try this:
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
// Capture the element name before pushing past it.
var elementName = reader.Name;
reader.Read();
//Response.Write(reader.Value + "</br>");
//Response.Write(reader.Depth);
switch (elementName)
{
case "Id":
Response.Write(reader.Value);
break;
case "Name":
Response.Write(reader.Value);
break;
}
}
}
The key to finding this sort of thing, is to debug carefully. Start with a cut down xml file and either actually step through in the debugger, or write debug output to a log or the response. It'll make identifying these sort of issues much easier.
Since it is working outside switch, I guess than name of the node is of different case.Check the case of the nodes
Edit:
You are calling reader.read() twice and the reader.value will not return proper value for an element.
If you still want to use xmlreader check the below code
XmlTextReader reader = new XmlTextReader(<XML Path>)
while (reader.Read())
{ if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "Id": Response.Write(Server.HtmlEncode(reader.ReadString()) + "</br>");
break;
case "Name": Response.Write(Server.HtmlEncode(reader.ReadString()) + "</br>");
break;
}
}
}
reader.Close();
I would suggest that you take a look at XML (de)serialization instead of using XmlReader. .Net will verify the xml and you will more easily be able to debug the Xml input.
You simply create a class with fields mirroring your Xml structure and use the following code:
class searchResult
{
public List<item> itemList { get; set;}
}
A complex field class example
class item
{
public int Id { get; set; }
public string Name{ get; set; }
}
The actual work gets done like so:
XmlSerializer SerializerIn = new XmlSerializer(typeof(SerializeTest));
FileStream fs = new FileStream(#"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
SerializeTest loadTest = (SerializeTest)SerializerIn.Deserialize(fs);
fs.Close();
Where SerializeTest is the class your loading the xml into. It is much easier to work this way, because you never need to deal with the raw Xml unless it is invalid.
You can find more info here: http://www.codeproject.com/Articles/4491/Load-and-save-objects-to-XML-using-serialization
Probably a better tutorial: https://web.archive.org/web/20211020113423/https://www.4guysfromrolla.com/webtech/012302-1.shtml

Problem with extracting files with DotNetZip. It doesn't extract files. what's the problem?

private void ZipExtract(string zipfilename)
{
var path = Server.MapPath(#"~/Files");
ZipFile zip = ZipFile.Read(zipfilename);
zip.ExtractSelectedEntries("name=*.jpg,*.jpeg,*.png,*.gif,*.bmp", " ", path,ExtractExistingFileAction.OverwriteSilently);
}
[HttpPost]
public ContentResult Uploadify(HttpPostedFileBase filedata)
{
var path = Server.MapPath(#"~/Files");
var filePath = Path.Combine(path, filedata.FileName);
if (filedata.FileName.Contains(".zip"))
{
ZipExtract(filedata.FileName);
}
filedata.SaveAs(filePath);
}
what's the error you see? Exception? Other condition? You need to add some additional context to your question. But there are a couple things that stick out even without a better description.
employ a using() clause with the ZipFile class; it is IDisposable.
It looks like you try to extract the zip file before you call .SaveAs(). If I read your code correctly, that means the ZipFile.Read() is trying to read a file that has not yet been created. If that is the case it will throw a FileNotFoundException. I may be wrong about this; more text from you would help clarify.

How to rename a file in C#

Consider:
strPath= c:\images\gallery\add.gif
I need to rename this file from add.gif to thumb1.gid, and I should write one command method, whatever the file name. We need to
replace that name with this like below.
string strfilename = **"thumb"**
****Result thum.gif**
strPath= c:\images\gallery\thum.gif **
You have several problems, looking up the value in the XML file, and renaming the file.
To look up the number corresponding to Gallery2 or whatever, I would recommend having a look at Stack Overflow question How to implement a simple XPath lookup which explains how to look up nodes/values in an XML file.
To rename a file in .NET, use something like this:
using System.IO;
FileInfo fi = new FileInfo("c:\\images\\gallery\\add.gif");
if (fi.Exists)
{
fi.MoveTo("c:\\images\\gallery\\thumb3.gif");
}
Of course, you would use string variables instead of string literals for the paths.
That should give you enough information to piece it together and solve your particular lookup-rename problem.
I created a utility method to help encapsulate how to rename a file.
public class FileUtilities
{
public static void RenameFile(string oldFilenameWithPathWithExtension, string newFilenameWithoutPathWithExtension)
{
try
{
string directoryPath = Path.GetDirectoryName(oldFilenameWithPathWithExtension);
if (directoryPath == null)
{
throw new Exception($"Directory not found in given path value:{oldFilenameWithPathWithExtension}");
}
var newFilenameWithPath = Path.Combine(directoryPath, newFilenameWithoutPathWithExtension);
FileInfo fileInfo = new FileInfo(oldFilenameWithPathWithExtension);
fileInfo.MoveTo(newFilenameWithPath);
}
catch (Exception e)
{
//Boiler plate exception handling
Console.WriteLine(e);
throw;
}
}
}
I omitted several other file system checks that could optionally be done, but as #JoelCoehoorn pointed out in a comment on this page, the File System is Volatile, so wrapping it in a try-catch may be all that is necessary.
With that class in your library, now you can simply call:
var fullFilename = #"C:\images\gallery\add.gif";
var newFilename = "Thumb.gif";
FileHelper.RenameFile(fullFilename,newFilename);

Resources