I am facing a very strange issue of renaming images (please see screenshot)
when i click up/down buttons i rename both images to swap them.
first two three times it works perfectly, but when i repeat this process it stops changing the images in the browser.
Further investigating i found that my code is working pefectly but the browse is caching the images that's why they dont change their position.
when i press cTRL + F5 i see changed images or if i move to any other page and come back to same page i again see right order of images, but on same page it does'nt happen :(
any one can put some light on it? how can i resolve this issue?
Code of swapping:
protected void rptImages_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["Id"]);
String path = Server.MapPath(e.CommandArgument.ToString());
if (e.CommandName == "Up")
{
SwapImagesOnUpClick(id, path);
}
if (e.CommandName == "Down")
{
SwapImagesOnDownClick(id, path);
}
}
public void SwapImagesOnUpClick(int id, string path)
{
string oldFileName;
string newFileName;
string tempFileName;
string basicPath = path.Substring(0, path.LastIndexOf('\\'));
oldFileName = path.Substring(path.LastIndexOf('\\') + 1);
tempFileName = "temp.jpg";
//get new filename
string[] fileParts = oldFileName.Split('.');
newFileName = (Convert.ToInt32(fileParts[0]) - 1).ToString();
string newFilePath = basicPath + "\\" + newFileName + ".jpg";
string tempFilePath = basicPath + "\\" + tempFileName;
// set already existing newfilename to temp
File.Move(newFilePath, tempFilePath);
File.Move(path, newFilePath);
File.Move(tempFilePath, path);
}
I suggest that you to change the location of image1 to location image2 inside the generated page instead of renaming the files
if somebody have to face similar situation as mine just append: "?timestamp"
in image src in this way your image wont get cached and everything will work perfectly to achieve up and down image functionality using ajax.
Related
I don't know if it's possible, but i wanted to ask and get some help.
So i have an .txt file inside my solution, and i was wondering if it would be possible to move it to desktop by a button in my C# Program. Picture to Solution Item
So let's say i compiled my C# Project, i would want it to by a button press to move that .txt file to desktop that is inside my Program.
Like a VirtualBox that enigma has.
What i have tried is, but whenever i run program it just tries to find the .txt file externally, and not the one inside the program.
private void Button_Click(object sender, EventArgs e)
{
string sourcePath = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
string destinationPath = #"C:\";
string sourceFileName = "TextFile1.txt";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Returns
Picture of error
Best Regards.
The program below creates a snapshot of itself by pressing the P key. It creates the file in the directory the program is in. For example the first time you press the P key it creates the file snapshot.png, if you press it again it creates snapshot_1, third time snapshot_2 and so on...
But if you close the program and start it again and those files are existing now in the directory, if now you press P key it overwrites them...
What I want is the program to check if the file that it tring to create exist, and if so, to try to create a file with the next number in the row.. and if that exist too, then try the next, and so on, untill it finds a file name that not exist and only then to create the file.
Can you help me modify the code to do what i'm describing?
string filename = "\\screenshot.png";
private void Mainwindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.P)
{
FrameworkElement element = UxVisual as FrameworkElement;
var pathstr = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
filename = "\\screenshot_" + DateTime.Now.ToFileTime() + ".png";
Uri path = new Uri(pathstr + filename);
CaptureScreen(element, path);
}
I dont know why this question turned out to be so offensive in the commentsection above...
However as other users already suggesteted you should consider to add a timestampt to your filepath.
You can do this using DateTime and a string operation like this:
filename = "\\screenshot_" + DateTime.Now.ToFileTime() + ".png";
possible output would be a file named screenshot132006693766467910.png this will cause all filenames to be different from ech other and not to overwrite each other
as requested you can make it look a lit better using this:
var filename = "\\screenshot_" + DateTime.Now.ToString("HH_mm_ss_fff") + ".png";
output will be like screenshot_16_14_11_523.png containing the hour minute second and milliseconds
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}
I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)
Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);
You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));
Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.
I have a field in my app (c#) to save an image into the database. I written the following code to save the image into a folder and then save the path into the database. But the image is not getting saved into the folder.
string imgName = FileUpload1.FileName.ToString();
string imgPath = null;
if (imgName == "")
{
//int taxiid = Convert.ToInt32(HiddenField1.Value);
Taxi t = null;
t = Taxi.Owner_GetByID(tx.Taxi_Id, USM.OrgId);
imgPath = t.CarImage;
}
else
{
imgPath = "ImageStorage/" + imgName;
}
FileUpload1.SaveAs(Server.MapPath(imgPath));
tx.CarImage = imgPath;
I think your problem is that you add the name to the Path I try it and for me it works fine if I save it like this:
FileUpload1.SaveAs(Server.MapPath("ImageStorage") + imgName);
And as #Rahul mentioned add a try catch to prevent errors.
And you check
if (imgName == "")
According to my understanding it's not posible that imgName is "" but anyway you better add a check if the fileupload has a file.
if (FileUploadControl.HasFile)