Open image in Windows Photo Viewer - c#

How to open .jpg image in Windows Photo Viewer from C# app?
Not inside app like this code,
FileStream stream = new FileStream("test.png", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(stream);
stream.Close();

I think you can just use:
Process.Start(#"C:\MyPicture.jpg");
And this will use the standard file viewer associated with .jpg files - by default the windows picture viewer.

Start it in a new Process
Process photoViewer = new Process();
photoViewer.StartInfo.FileName = #"The photo viewer file path";
photoViewer.StartInfo.Arguments = #"Your image file path";
photoViewer.Start();

The code fetch photo from ftp and shows the photo in Windows Photo Viewer.
I hope it will usefully for you.
public void ShowPhoto(String uri, String username, String password)
{
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential(username,password);
byte[] imageByte = ftpClient.DownloadData(uri);
var tempFileName = Path.GetTempFileName();
System.IO.File.WriteAllBytes(tempFileName, imageByte);
string path = Environment.GetFolderPath(
Environment.SpecialFolder.ProgramFiles);
// create our startup process and argument
var psi = new ProcessStartInfo(
"rundll32.exe",
String.Format(
"\"{0}{1}\", ImageView_Fullscreen {2}",
Environment.Is64BitOperatingSystem ?
path.Replace(" (x86)", "") :
path
,
#"\Windows Photo Viewer\PhotoViewer.dll",
tempFileName)
);
psi.UseShellExecute = false;
var viewer = Process.Start(psi);
// cleanup when done...
viewer.EnableRaisingEvents = true;
viewer.Exited += (o, args) =>
{
File.Delete(tempFileName);
};
}
Best Regards...

public void ImageViewer(string path)
{
Process.Start("explorer.exe",path);
}
Path is the file path of the image to be previewed.

I am trying the other answers but they all return the same error about how the location isn't an OS App, so I'm not sure where the issue lies. I did however discover another method to open the file.
string Location_ToOpen = #"The full path to the file including the file name";
if (!File.Exists(Location_ToOpen))
{
return;
}
string argument = "/open, \"" + Location_ToOpen + "\"";
System.Diagnostics.Process.Start("explorer.exe", argument);
It starts out by testing if the file exists or not. If it doesn't exist it would have caused an error.
After that it simulates a "open" request on a file explorer without opening a file explorer, then the system opens the file with the default app.
I am currently using this method in my project so I hope it works for you too.

Related

How can I delete the old one while uploading a new image with c #

I want to delete old image when uploading new one with c# but I get
the process cannot access the file because it is being used by another process. error
public void DeleteExistImage(string imageName)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/" + imageName);
using (var stream = new FileStream(path, FileMode.Create))
{
stream.Dispose();
System.IO.File.Delete(path);
}
}
Try this to delete the file and then create a new file
string path = #"c:\mytext.txt";
if (File.Exists(path))
{
File.Delete(path);
}
Also, look into the thread if it solves your issue
IOException: The process cannot access the file 'file path' because it is being used by another process

getting an error that 'the process cannot access the file because it is being used by another process' in my dot net program

I tried 'using' but it says that the method is not Idisposable. I checked for running processes in Task Manager, nothing there. My goal is to upload a file from local directory to the Rich Text editor in my website. Please help me resolve this issue. Thanks in Advance
public void OnPostUploadDocument()
{
var projectRootPath = Path.Combine(_hostingEnvironment.ContentRootPath, "UploadedDocuments");
var filePath = Path.Combine(projectRootPath, UploadedDocument.FileName);
UploadedDocument.CopyTo(new FileStream(filePath, FileMode.Create));
// Retain the path of uploaded document between sessions.
UploadedDocumentPath = filePath;
ShowDocumentContentInTextEditor();
}
private void ShowDocumentContentInTextEditor()
{
WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions();
Editor editor = new Editor(UploadedDocumentPath, delegate { return loadOptions; }); //passing path and load options (via delegate) to the constructor
EditableDocument document = editor.Edit(new WordProcessingEditOptions()); //opening document for editing with format-specific edit options
DocumentContent = document.GetBodyContent(); //document.GetContent();
Console.WriteLine("HTMLContent: " + DocumentContent);
//string embeddedHtmlContent = document.GetEmbeddedHtml();```
//Console.WriteLine("EmbeddedHTMLContent: " + embeddedHtmlContent);
}
FileStream is disposable, so you can use using on it:
using (var stream = new FileStream(filePath, FileMode.Create)
{
UploadedDocument.CopyTo(stream);
}

Show image from picture box?

I have project with C#. I add picture box control to show images are coming from the database.
I have a DbComand that executes "select * from Client "; and a DataReader to read the results:
byte[] buffer = (byte[])dr[24];
if (buffer != null)
{
groupBox1.Visible = true;
MemoryStream ms = new MemoryStream(buffer);
pictureBox1.Image = Image.FromStream(ms);
}
How I can open Windows Photo Viewer with the image that display in the picture box...
You can open it with below Code:
Process.Start(#"C:\Picture.jpg");
You can save the image form the Picturebox to a temporary file and show that by running the PhotoViewer dll. That can be done with the rundll32 helper by using the Process class. Your code would look like this:
// get a tempfilename and store the image
var tempFileName = Path.GetTempFileName();
pictureBox1.Image.Save(tempFileName, ImageFormat.Png);
string path = Environment.GetFolderPath(
Environment.SpecialFolder.ProgramFiles);
// create our startup process and argument
var psi = new ProcessStartInfo(
"rundll32.exe",
String.Format(
"\"{0}{1}\", ImageView_Fullscreen {2}",
Environment.Is64BitOperatingSystem?
path.Replace(" (x86)",""):
path
,
#"\Windows Photo Viewer\PhotoViewer.dll",
tempFileName)
);
psi.UseShellExecute = false;
var viewer = Process.Start(psi);
// cleanup when done...
viewer.EnableRaisingEvents = true;
viewer.Exited += (o, args) =>
{
File.Delete(tempFileName);
};
See this answer for how the Photoviewer can be started from the commandline.
If you are working in a forum application you can add a picturebox with the toolbox, if u did that go to your properties of the picturebox and press the three dots next to the name image in your properties by doing that. Press local resource and you are in your own documents. hope this helped you

Download PDF file from Web location and Prompt user SaveAs box on client in web-Application ASP C#

I have link of a PDF file located on a website e.g. (https://www.mysite.com/file.pdf).
What I need is prompt the user (on Client side) the SaveAs box to choose the file location to save the file.
I tried the SaveFileDialog , but got know that it is only for Windows Forms. and my application is web based.
C# Code
var fileNumber = lblFileNumber.Text;
string fileDownloadLink = "http://www.mysite.com/" + fileNumber + ".pdf";
string fileName = fileNumber + ".pdf";
bool exist = false;
try
{
var request = (HttpWebRequest)System.Net.WebRequest.Create(fileDownloadLink);
using (var response = (HttpWebResponse)request.GetResponse())
{
exist = response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
if (exist)
{
var wClient = new WebClient();
wClient.DownloadFile(fileDownloadLink, fileName);
}
I wrote the above code, it does check if the file is exist on the file location, but
how to prompt user to choose the location to where he want to save file and save on his local hard drive?
It is not possible to do that. When the user wants to download a file, the browser will decide how to show it to the user.
Write a file from disk directly:
HttpContext.Current.Response.TransmitFile(#"C:\yourfile.pdf");
Or from another source, loaded as a byte array:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(bytesOfYourFile);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

process cannot access the image file because it is being used by another process

i downloaded images from my deployed website and save it into my WPF app folder , basically i am running 2 platforms , a website and WPF . What i am trying to do is users uploaded their images using the web , so on the WPF side , i download the image from the web and display on my WPF app but i got this error :
The process cannot access the file
'C:\Users\apr13mpsipa\Desktop\OneOrganizer\OneOrganizer\bin\Debug\TaskImage\Fill
in the blanks.jpg' because it is being used by another process.
This is the code :
protected void DownloadData(string strFileUrlToDownload, string taskName)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Flush();
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite)) // ERROR HERE
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
I got the error when i try to display a image on a first button click , then i display the image again on the other button . basically this happens when i try to display the image 2 times.
---EDIT ------
Updated as of baldrick's comment :
DownloadData(fileUploadDirectory + daoTask.GetImage(aid, actTask.taskID).Substring(1), daoTask.GetTaskName(aid, actTask.taskID));
Image imgActivityTask = new Image();
imgActivityTask.Height = 90;
imgActivityTask.Width = 90;
imgActivityTask.Margin = new Thickness(10);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(currentpath, UriKind.Absolute);
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.EndInit();
imgActivityTask.Source = img;
Its still giving me the same error on the using line.
In you WPF code, you might need to specify the IgnoreImageCache setting:
yourImage.CacheOption = BitmapCacheOption.OnLoad;
yourImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache
This might force it to load, and not lock the file.
The answer here deals with the same problem.
I am guessing you are leaving the file stream open.
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Thanks

Categories