WPF C# Opening files in multiple directories - c#

I have 3 open file buttons which open a file open dialog, whenever one file is opened the starting directory for the next button is always the same as the last button that was used.
I need to be able to have each button open only the last directory that it was associated with, not what the last button opened was associated with.
How can make each dialog open in the directory that that specific dialog was opened in last?
Example, I have 3 buttons i want to open in the following order:
Btn1 Open File in dir C:\temp\1 then
Btn2 Open File in dir C:\temp\1 then change to C:\temp\2
Btn3 Open File in dir C:\temp\2 then change to C:\temp\3
Btn1 Open File in dir C:\temp\1 NOT in C:\temp\3

declare some private fields in your class:
string startLocationForDialog1 = "C:\";
string startLocationForDialog2 = "C:\";
string startLocationForDialog3 = "C:\";
Then in your methods, when you create the open file dialog, set the starting location to the value of the corresponding variable.
After the file is selected, save the location of the file (without the file name) in the corresponding variable. Next time you press the same button, you use that variable which contains the last location from which a file was selected.

Related

How do I, in a compiled C# class, read a file using System.IO from another directory outside my main directory without typing the whole path?

If my directories look like this:
MyProject
MyProject
some_dir
file_I_wanna_read
here
Here.cs
How do I read file_I_wanna_read from Here.cs, without having to type the whole path?
(eg. "C:\my_user\Projects\MyProject\MyProject\some_dir\file_I_wanna_read")
I've already tried writing the path as if I were at the solution:
MyProject\some_dir\file_I_wanna_read
And also as if I were in the .csproj:
some_dir\file_I_wanna_read
But those don't work.
Here's a solution.
It relies on getting the FileYouWantToRead copied into the EXE's location where it's findable.
Create a simple, out-of-the-box WinForms app.
Right-click the project, select Add then New Folder, name the folder "SomeDir"
Right-click the new "SomeDir" folder and select Add and then New Item
In the dialog that pops up, search for "Text", pick Text File and name the file "FileIWantToRead.txt"
When the file opens, type "This is the file I want to read" and save the file
Right-click the new "FileIWantToRead.txt" file and choose properties
In the properties pane, set Build Action to Content and Copy to Output Directory to Copy Always
Go back to the form designer, drop a button and a label control on the form
Double-click the button
In the "Form1.cs" button click handler that opens, put this code:
Form1.cs button click handler:
private void button1_Click(object sender, EventArgs e)
{
var fullExeName = Assembly.GetExecutingAssembly().CodeBase;
if (fullExeName.StartsWith("file://"))
{
fullExeName = fullExeName.Substring(8);
}
var exeDir = Path.GetDirectoryName(fullExeName);
var fileName = Path.Combine(exeDir, "SomeDir", "FileIWantToRead.txt");
var content = File.ReadAllLines(fileName)?.First();
label1.Text = content ?? "Not Found";
}
The "Copy Always" action will cause your text file to get copied to the output EXE's folder. In this case, since it's within the "SomeDir" folder, it will get copied into a "SomeDir" folder under the output folder.
I get the EXE's folder from the executing assembly (i.e., the running exe) and use the various utilities in System.IO to get the right folder and file names. After clicking the button, the first line of that file will show in the label.
First you can get current directory of your program. (Read these official docs for further help)
Then you can access your file with directory related to current directory.
Your string of directory accessing should be something like this:
..\some_dir\file_I_wanna_read
(Double dots mean go one directory backward or up.)

save and save as in Windows Form App by C#

I'm using this code for making save as of image in c#
SaveFileDialog svf = new SaveFileDialog();
svf.Filter = "JPEG files (*.jpeg)|*.jpeg";
if (DialogResult.OK == svf.ShowDialog())
{
this.imgbox.Image.Save(svf.FileName,ImageFormat.Jpeg);
}
I need to make save now for image without change name or location ( apply save not save as as the above code ) how i can use this code for save now ?
Assuming WinForms, add a field or property to the appropriate control to hold the full path to the file currently opened, and call it currentFileName or something.
When opening a file, assign the path to the variable. Now when the user hits the Save menu, you can use the already stored path to overwrite the opened file. You can add a Save As menu that pops up the SaveFileDialog, and afterwards assigns the result to the variable again - if not cancelled.
When the user invokes the New or Close menu, make sure to clear the stored path.

Adding a pdf file into Visual Studio

I have a menustrip that has a tab I have created to be labeled "Contents". I want to be able to click on the Content tab and a window pop up with a pdf file listing the contents. I have the pdf file that lists the contents saved to my desktop. Is there a way to add this pdf file to visual studio so that when I click on the Content tab, the pdf file will be opened?
I do not want to have to click another button to search my computer for the file such as using OpenFileDialog. I just want to click the Contents tab and have it open a window with the pdf file.
There are multiple ways of doing that.
1) One way would be to launch a process from your app that will open the default registered viewer of PDF files (such as Adobe Reader) on your PC and pass the full path to the PDF file as a parameter:
Here you can find out ho to determine the path to the default handler application by file extension (".pdf" in your case):
http://www.pinvoke.net/default.aspx/shlwapi/AssocQueryString.html
string execPath = GetAssociation(".pdf");
Once you know the path to the executable, you can launch it with a path to your PDF file as a parameter:
using System.Diagnostics;
...
// Start new process
Process.Start(execPath, "C:\\myfile.pdf").WaitForExit(0);
2) Another way would be to create a Windows form in your app and add web browser control to it. The web browser control can then be programmatically "navigated to" your specific PDF file. That is assuming that your Internet Explorer can display PDF files already by using something like Adobe Reader within its window, i.e. as an inline attachment:
Add a reference from your project to Microsoft Internet Controls 1.1 (Right-click on References > Add reference... > COM).
In your form code (here panePdfViewer is a placeholder System.Windows.Forms.Panel control):
private AxSHDocVw.AxWebBrowser axWebBrowser;
...
private void InitializeWebControl()
{
this.SuspendLayout();
this.axWebBrowser = new AxSHDocVw.AxWebBrowser();
((ISupportInitialize)(this.axWebBrowser)).BeginInit();
this.axWebBrowser.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom)
| AnchorStyles.Left)
| AnchorStyles.Right)));
this.axWebBrowser.Enabled = true;
this.axWebBrowser.Location = this.panelPdfViewer.Location;
this.axWebBrowser.Size = this.panelPdfViewer.Size;
((ISupportInitialize)(this.axWebBrowser)).EndInit();
this.axWebBrowser.Visible = false;
this.Controls.Add(this.axWebBrowser);
this.ResumeLayout(false);
}
and then:
// Clear browser
object blank = "about:blank";
this.axWebBrowser.Navigate2(ref blank);
// Display file
object loc = "file:///" + System.IO.Path.GetFullPath(fileName).Replace('\\', '/');
object null_obj_str = null;
object null_obj = null;
this.axWebBrowser.Navigate2(ref loc, ref null_obj, ref null_obj, ref null_obj_str, ref null_obj_str);
3) A third way is to use a third party control library that can display PDF files.

How to create a save button that overwrites previously selected file

How would you make a Save button that, unlike a SaveAs button, will save over the previously selected file without opening a dialog? I have no trouble utilizing SaveAs to open a Save Dialog and create a file but automatically saving to a previously set text file has stumped me.
did you try something like that :
System.IO.File.AppendAllText(previously file path, the new value);

how can I upload a file via file input box using webbrowser in C#

May be this question is asked in past but I have searched and not found its solution yet.
I have tried all the options that I have found till now but all in vain.
SendKeys doesn't work as it does not fill the file input box with file path, that is to be uploaded.
Cannot set file input box "SetAttribute" value as there is no value attribute available:
thats all.
If I use element.focus() it pops up "choose file to upload" dialog and now I don't know how to fill it programmatically and open it in file input box.
I want it to be automated completed so that user does not have to interact with the application.
Application shall pick the file from hard disk from given file path and fill other fields of form then start uploading, all using webbrowser control in windows form application.
No solutions found!
Can anyone help please? (This is my first ever question on stackoverflow, therefore if I am doing anything wrong then please guide, I mean if I am not allowed to post such question!)
Here is the code:
HtmlElementCollection heCollection = doc.GetElementsByTagName("input");
foreach (HtmlElement heSpan in heCollection)
{
string strType = heSpan.GetAttribute("type");
string strName = heSpan.GetAttribute("name");
if (strType.Equals("file") && strName.Equals("file"))
{
heSpan.Focus();
//heSpan.SetAttribute("value", "test.jpg");
SendKeys.Send("C:\\1.txt");
//heSpan.InnerText = "c:\\1.txt";
}
//Title for the attachment
if (strName.Equals("field_title"))
{
heSpan.InnerText = "1.txt";
}
}
When this code executes, cursor starts blinking in fine input box (as I have set heSpan.focus()) but the file path doesn't show in the file input box.
If I implement
heSpan.InvokeMember("click");
It opens the choose a file to upload dialoge/popup window and there I get stuck, because I don't know how to fill that popup dynamically and then insert the file path in file input box.
Try setting the focus to the WebBrowser control right before you set the focus to the input field.
That worked for me.

Categories