How to delete a file while the application is running - c#-3.0

I have developed a C# application, in the application the users choose a photo for each record. However the user should also be able to change the pre-selected photo with a newer one. When the user changes the photo the application first deletes the old photo from the application directory then copies the new photo, but when it does that the application gives an exception because the file is used by the application so it cannot be deleted while the application is running. Does any one have a clue how to sort this out? I appreciate your help
This is the exception
The process cannot access the file
'D:\My
Projects\Hawkar'sProject\Software\Application\bin\Debug\Photos\John
Smith.png' because it is being used by
another process.
//defining a string where contains the file source path
string fileSource = Open.FileName;
//defining a string where it contains the file name
string fileName = personNameTextBox.Text + ".png" ;
//defining a string which specifies the directory of the destination file
string fileDest = dir + #"\Photos\" + fileName;
if (File.Exists(fileDest))
{
File.Delete(fileDest);
//this is a picturebox for showing the images
pbxPersonal.Image = Image.FromFile(dir + #"\Photos\" + "No Image.gif");
File.Copy(fileSource, fileDest);
}
else
{
File.Copy(fileSource, fileDest);
}
imageIDTextBox.Text = fileDest;

First of all, you code is not good.
The new image is only copied if there is currently no image (else).
But if there is an old image, you only delete this image, but never copy the newer one (if).
The code should better look like this:
if (File.Exists(fileDest))
{
File.Delete(fileDest);
}
File.Copy(fileSource, fileDest);
imageIDTextBox.Text = fileDest;
This code should work, but if you are getting an exception that the file is already in use, you should check "where" you use the file. Perhaps you are reading the file at program start. Check all parts of your program you are accessing these user files if there are some handles open.

Thanks a lot for your help and sorry for the mistake in the code I just saw it, my original code is just like as you have written but I don't know maybe when I posted accidentally I've put like this. when the application runs there is a picturebox which the image of each record is shown, that is why the application is giving an exception when I want to change the picture because it has been used once by the picturebox , however I've also tried to load another picture to the picture box before deleting the original one but still the same. I've modified the above could if you want to examine it

Related

Swift 2.0 - Unable to Write to Text File (OS X)

I have a text file that I will be reading and writing to. I have gotten the code to read successfully, but am unable to write to the text file again. I want to overwrite everything (not amend).
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent("airports.txt")
var strTextToWrite:String = String()
strTextToWrite = "Test"
do {
try strTextToWrite.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch { print("Error") }
}
The above code doesn't throw an error (i.e. the word 'Error' isn't printed as per my catch code), but the text file remains unedited, retaining the value it had before the code was run.
The text file is contained inside the X-Code project as shown below:
I'm at a real loss here, I don't understand why the code isn't working. I have confirmed that it is being run (by printing the value of strTextToWrite before and after the do statement, and it is definitely running through the do block of code because it isn't being caught by the catch block. The only thing I can think of is that the code is pointing at the wrong file (but the file name is correct, as you can verify with the screenshot above).
What am I doing wrong? Thanks in advance.
You are looking at 2 different files: the one you write to is ~/Documents/airport.txt while the one you see (and check) in Xcode is located in your project folder. To see the update, you need to reference the file in Xcode, not make a copy of it.
Right click airport.txt in your Project Navigator and click Delete > Move to Trash
Go to ~/Documents/airport.csv and drag it into your Xcode project. Do not add it to any target and unselect "Copy Items if Necessary"
You now have created a link to the file.
Modifying files in your bundle is generally a bad idea. If you need a place to output a temporary file, use the app's subfolder under ~/Application Support or the system's temp folder.

Canon EDSDK sample code - help to understand save file to location

I am new to the EDSDK, but so far have been very happy with the results. I have my program working just fine saving to the camera, however when I set to saveTo Host I'm unclear on where it thinks it's supposed to save to.
Everything appears to work. Callback function gets called, progress bar animates but I have no idea where it thinks it's pointing the file to.
the closest I get is finding where the #"download" command is issued, the argument to this call should be getting cast as a (EdsDirectoryItemRef)
This all seems to be coming from the EDSCALLBACK handleObjectEvent but I can't figure out how it gets constructed.
Ideally I'd like to be able to specify where on disk I want the images to go. Can someone provide some aid?
[edit]
Okay, I see the images are going into the build directory, but perhaps someone could help me to understand why. Or even better how to specify a path for myself.
When you set saveTo_Host, the image is stored on a temporary memory in the camera. The camera then triggers a DirItemRequestTransfer event that would call the callback function 'handleObjectEvent'. The reference to the image, stored in the temporary camera memory, is passed to the callback function.
Within the handleObjectEvent callback function you probably would be creating a file stream and using EdsDownload to download the file to the location on the PC (which is specified by the file stream).
When you create a file stream you need to specify a file name (the first argument). This file name determines where the image would be stored. If you just specify the file name without a path the image gets stored in the build directory. If you would like to save the file in a particular location you need to specify the file name along with its path.
Hope this helps.

UIWebView loading a local image that gets overwritten but it doesn't refresh

My problem is this
I'm loading an html string into an UIWebView, in which i'm referencing a local image from my application's Documents folder.
<html><body><img src="image.png"/></body></html>
It loads just fine, no problems with the baseUrl or anything. The problem is when I do some stuff and generate a new image, with the same name, and save it in the same Documents folder, overwriting the old one (I delete the old one if it exists and save the new one).
Now, with the UIWebView still loaded on the screen, if I do a [webview reload] or manually load the html string again, I still get the old image, the one I have just overwritten.
I already checked in the simulator folder, the image.png there is indeed the new image, not the old one. And I already did everything imaginable to stop the webview from caching.
Of course, if I save the new image with a different name, say "image2.png", and reload the html string with src="image2.png", it all shows up ok.
What am I missing here?
Try appending a random query string to your image source.
ie.
function ImageSource(src){
return src + "?time=" + (new Date()).getTime().toString();
}
function ForceImageReloads(){
var images = document.getElementsByTagName("img");
for (var i=0;i<images.length;i++){
var img = images[i];
var s = img.getAttribute("src");
img.src = ImageSource(s);
}
}
ForceImageReloads();
Or something similar to that :)
This maybe a problem with the simulator. I had something similar once. Try running your code on a real device. For me, the simulator seem like it is lazy to reload data that have the same name.

OpenXML: Issue adding images to documents

Up until now, this block of code has been using to build documents with text for several months with no snags. I am now trying to dynamically add images. I've spent about two days staring at code and researching and am at an end. I suspect the issue is that relationships are not being created (more details below.) Maybe not?
//set stuff up...
WordprocessingDocument doc = WordprocessingDocument.Open(fsPat, true, new OpenSettings(){
AutoSave = true,
MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts,
DocumentFormat.OpenXml.FileFormatVersions.Office2007),
MaxCharactersInPart = long.MaxValue
});
MainDocumentPart mainPart = doc.MainDocumentPart;
.
.Other stuff goes here
.
//now the fun...
Run r2 = new Run();
// Add an ImagePart.
ImagePart ip = mainPart.AddImagePart(ImagePartType.Png);
string imageRelationshipID = mainPart.CreateRelationshipToPart(ip); //
using (Stream imgStream = ip.GetStream())
{
System.Drawing.Bitmap b = new System.Drawing.Bitmap("myfile.png");
b.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png);
}
Drawing drawing = BuildImage(imageRelationshipID, "name"+imageRelationshipID.ToString(), 17, 17);
r2.Append(drawing);
p.Append(r2);
The image part is essentially copied from http://blog.stuartwhiteford.com/?p=33) and is running in a loop presently. I also copied his BuildImage() function and use it as-is.
When I open the resulting docx, I see red Xs where the images are saying "This image cannot currently be displayed."
When I open the zip, the images will appear in root/media, but not root/word/media as I'd expect. I also cannot find the images referenced in any of the relationship files. Ideally they'd be in root/word/_rels/document.xml.rels. You'll notice I changed how imageRelationshipID is set hoping to fix this. It didn't.
Please help. Thank you.
So... It seems like OpenXML just hates me. I copied AddImagePart code from like 3-4 places among trying other things--none of which lasted long--and just could not get relationships to form. The implication I see is that they happen automatically with the AddImagePart function.
I ended up doing a complete workaround where I add all the pictures I might want to put and remove the Drawing nodes' parents of the ones I didn't want (Run nodes, generally.) Since these are very small pictures, it's feasible and in ways more elegant than trying to add them as necessary since I don't have to keep track of where images are stored on disk.

SWFUpload + jQuery.SWFUpload - Remove File From Queue

I'm facing a big issue IMO.
First, here's my code:
.bind('uploadSuccess', function(event, file, serverData){
if(serverData === 'nofile') {
var swfu = $.swfupload.getInstance('#form');
swfu.cancelUpload(file.id); // This part is not working :(
} else {
alert('File uploaded');
}
})
In this part I'm checking server response (I'm have strict validation restrictions). Now my question. Is it possible to remove uploaded file from queue? Basically, if server returns error I display error message, but... this file still exsit in the queue (I've implemented checking filename and filesize to avoid duplicated uploads) and user is not possible to replace this file (due to upload and queue limit).
I was trying to search for a solution, but without success. Any ideas?
Regards,
Tom
From the link
http://swfupload.org/forum/generaldiscussion/881
"The cancelUpload(file_id) function
allows you to cancel any file you have
queued.
You just have to keep the file's ID
value so you can pass it to
cancelUpload when you call it."
Probably you have to keep the file ID before sending anything to the server