Locating a file directory to display pdf in c# - c#

I am having a problem with displaying a pdf in my form wen a menu item is clicked
the directory im using cant be found
the file is in the project folder
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"\\ColsTechieApp\\TechnicianApplicationUserManual.pdf");
}
when i enter the full location
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"C:\Users\UV Chetty\Dropbox\Final\Complete\ColsTechieApp (Complete)\ColsTechieApp\Technician Application User Manual.pdf");
}
it works how do i make the path exclusive to the project folder

Try using Environment.CurrentDirectory as your current set and combin it with Path.Combine
Should work, becaus you are using full path

First, you're trying to escape backslashes but the # specifies that the string shouldn't be escaped. (Plus, you seem to be missing whitespaces)
Secondly, Environment.CurrentDirectory inserts the current path. Used with Path.Combine, you'll have your entire location.
If you're really lazy, you can skip the Path.Combine and directly concatenate strings. Process.Start() probably converts it to a Path automatically.

Related

Load External Files with C# (From Resource Folder)

I have a PDF file that I would like to load with a button click. I can reference the file in debug mode, but when I publish the project, the pdf doesn't migrate over or 'install' with the project.
The file is located in Resources/file.pdf
In the WPF form, I call the "OpenFile_Click" function on click.
Here is my function:
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
string appPath = AppDomain.CurrentDomain.BaseDirectory;
Process.Start(appPath + "Resources/file.pdf");
}
This clearly doesn't work to open that file. I can add ../../ in front of the Resources folder and it will open in debug, but that isn't very helpful.
So, what is the best option for opening an external file like a PDF?
After setting Properties\Copy to Output Directory = Copy if Newer as suggested by Clemens, I would also recommend the use of System.IO.Path.Combine to ensure the correct path delimiter for the platform.
If there is still an error when invoking the Process.Start then try starting "explorer.exe" with the combined file name. I successfully tested the following, see if you can repro.
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
var filePath = System.IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Resources",
"file.pdf"
);
Process.Start("explorer.exe", filePath);
}

How to include an excel file in the build windows form application

I have an excell file that I need to access via a button in my application. When debugging, I simply have to copy the file to the debug/bin directory and it works with this code:
private void button10_Click(object sender, EventArgs e)
{
string filename = "estimation 1.xls";
System.Diagnostics.Process.Start(filename);
}
but after building the project, I get a file cannot be found message when pressing the button. I tried including the file by dragging it into the solution manager but it still gives me the error. How can I include this excel file in the build? Will I need to change the code to access it?
Try the following if your spreadsheet is in the same directory as your application.
private void button10_Click(object sender, EventArgs e)
{
string fileName = Path.Combine(Application.StartupPath, "estimation 1.xls");
System.Diagnostics.Process.Start(fileName);
}
You will also need to import the System.Windows.Forms namespace at the top of your file.
using System.Windows.Forms;
Add File to Resources Folder
Change the property "copy to output directory" of file to copy
call with the process.Start, example:
public void openFile () {
System.Diagnostics.Process.Start ( Path.Combine ( Application.StartupPath, "Resources", "estimation 1.xls" ));
}

Open selected file from treeview in a richtextbox

My application consists of a TreeView a RichTextBox and a Button.
The TreeView displays contents(directories, folders and files) of my system.
The Button when pressed is supposed to take the selected file from the TreeView and display it in the RichTextBox.
I have used the following code:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath;
MessageBox.Show(a); //To check if it's taking the correct path
richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText);
}
The value in the string a is correct, that is TreeView.SelectedNode.FullPath returns the correct path which I confirm with the MessageBox.
However there is a runtime exception in the richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText) line.
It appends the path of the Debug folder before the actual selected file path(shown in the image), which leads to an exception.
All the files are stored locally.
How can I solve this problem?
It is because your tree nodes contains relative path to item instead of absolute.
How to prevent it? At first, you should store the full path (include drive name) in FullPath property.
If the path starts with the folder name, application tries to get the inner folder of current active folder (Debug). If the path starts with \ - app will seek the file in the root folder of current drive, if the path starts with drive name D:\ - app will seek the file on this drive. So, in your case, it will be better to pass absolute path always, it will exclude ambiguity while searching the file.
If the file should be stored relatively to the executive file, you should add some ..\ as prefix - it stands for 'going one level upper'
You can read this to get more familiar with windows pathname style.
After some research and trials I found the solution to this issue.
The reason behind this problem is that the code TreeView.SelectedNode.FullPath returns the path with an incorrect syntax.
Suppose the file you've selected in the TreeView has the path C:\Users\Admin\Desktop\test.txt
TreeView.SelectedNode.FullPath will return the path: C\Users\Admin\Desktop\test.txt which is syntactically incorrect i.e. it cannot be used directly in some other part of code.
The solution which I went for is, putting this output into a temporary string, and inserting :\\ in the 2nd place(1st index), thus making the syntax correct.(C:\\Users...)
Putting up the code I used just for reference:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath.ToString();
string b = ":\\";
string c = a.Insert(1, b);
richTextBox1.LoadFile(c, RichTextBoxStreamType.PlainText);
}
Hope this helps. Thank you for the assistance I received while solving this problem.

What is the difference between an absolute and a relative path?

I am asking because I am working on a project for school. Yes this is homework. But, I'm trying to understand a little bit more, though.
This is one example of what is being asked.
• When the user clicks the “Save” button, write the selected record to the file specified in txtFilePath (absolute path not relative) without truncating the values currently inside.
This is what I have,
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter myWriter = new StreamWriter(saveFileDialog1.FileName);
myWriter.Write(txtFilePath.Text);
myWriter.Close();
}
}
Now, I don't understand if I am doing this right. I know when I save it to my desktop and I delete it from my listbox and when I try to reload it again nothing shows up. This is what I have on my form,
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader myReader = new StreamReader(openFileDialog1.FileName);
txtFilePath.Text = openFileDialog1.FileName;
txtFilePath.Text = myReader.ReadToEnd();
myReader.Close();
}
}
And this is the load,
private void Form1_Load(object sender, EventArgs e)
{
string[] myFiles = Directory.GetFiles("C:\\");
foreach (string filename in myFiles)
{
FileInfo file = new FileInfo(filename);
employeeList.Items.Add(file.Name);
}
//...
Can someone please help me make sense of this?
Say you were giving directions to a spot. You have two methods you can describe getting to the location:
Relative to where you stand,
Relative to a landmark.
Both get you to the same location, but the former doesn't always work ("take a left, then a right, go through two lights then take another right" wouldn't necessarily work from the next town over, but works from where you stand). That's essentially the difference.
If you have C:\Windows\System32, that's an absolute path. If you have Windows\System32, it will only work so long as you're starting from C:\. If you start in C:\Program Files you would need a ..\ to get there correctly.
However, no matter where you are on the hard drive, C:\Windows\System32\ is a definitive way to get to that folder.
It's actually a simple distinction. A relative file path is going to be a structure based around a root node; and an absolute path is going to be a structure based on a non ambiguous location. That sounds kind of wonky, but it's actually pretty simple.
Here are some examples:
Absolute Paths
C:\inetpub\yourapplication\default.aspx
http://www.yourapplication.com/default.aspx
These paths are absolute because they are non ambiguous. Example 1 shows an absolute file path, and example 2 shows an absolute URL.
Relative Paths
./../script/something.js
~/default.aspx
A relative path specifies a location based on some known ahead point of reference. So in example 1, you know to go up one directory, then down into a directory called script, then to a javascript file. In example two, you are specifing the aspx page contained within the root of your application.
So, germane to your specific problem, you want to write a file to a specific absolute path, which means it needs to be a non ambiguous location.
An absolute path is the whole path name required to access the location in the file system.
For example: C:\Program Files\Internet Explorer\iexplorer.exe
Where as a relative path is in relation to some landmark, usually your main executable files location or the 'start in' location set when you open the program.
For example if your main executable is in C:\Program Files\ the relative path to iexplorer.exe is Internet Explorer\iexplorer.exe.
This is done usually when you don't always know where the file will absolutely be, like which drive letter it will be installed in or which folder it will be under.
However for a good example, if your file came with your program and you know your programs installation structure, you can use relative pathing to find all your files no matter where your program is installed as opposed to abolute pathing where your program would need to be installed in the exact same location each time.

How to delete 0KB text file

1) I am new to c sharp,
I am having a problem ,
I know how to delete the file,
I am using this line of code to delete the file,
private void button2_Click(object sender, EventArgs e)
{
File.Delete(a);
}
I want to know how to delete 0KB file.
2)and one more thing i want to know how many path we can save for our application like ,
private void button2_Click(object sender, EventArgs e)
{
String a = (String)(Application.StartupPath + "\\TEMP");
}
I think there are more paths like Application.StartupPath ,can anyone pls say how many ways are there to save a path like Application.StartupPath .
There would be a great appreciation if someone could help me,
Thanks in Advance,
You delete a 0KB file just like you delete any other file (i.e., File.Delete is correct). If the file cannot be deleted, it is probably in use. You can use Process Monitor to find out which process is using the file.
Other special paths can be obtained using Environment.GetFolderPath with the SpecialFolder enumeration.
EDIT (after reading the comments): If you want to delete all 0-length files in the directory, you can
use Directory.GetFiles to get a list of all the files in the directory,
use FileInfo.Length to get the size of the files, and then
use File.Delete to remove certain files.
In fact, the MSDN page on FileInfo.Length contains an example that outputs a list of files and their sizes in a given directory. You should be able to adapt this example to delete all files with 0 length.
In regards to you first question - you delete a 0 length file the same way you do any other file:
File.Delete(pathTo0LengthFile);
Your second question doesn't make sense. You can save your file in any path on the drive that the account the application runs under has write permissions to.
There are several system and special folders that you can get the path of use Environment.GetFolderPath - perhaps that's what you mean.

Categories