Get FilePath for my excel file with sheetname - c#

I am trying to do is to get filepath for my excel file. But I am unable to do so.
File is in Document/Visual Studio 2013/Project/ProjectName/a.xlsx
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/"),"a.xlsx");
string SheetName="Sheet1";
Is it wrong way to do it or is it correct way?

This is the better answer according to me.
Better to save in
C:\Users\AJ1110\Documents\Visual Studio 2013\Projects\Proj\Proj
And in
program.cs
string pathfile = #"..\..\a.xlsx";
string sheetName = "Whatever_SheetName_IS!!!";
This might solve your problem.

HttpContext.Current does not work outside of a web context.
If your project is running inside a console or windows program, it cannot work with HttpContext.Current. MapPath is meant to translate a web path to a file system path. ~/ is a .Net convention for pointing the root web path of a web application.
You should explicit what are your requirements about how to resolve the folder containing your file.
Maybe should you simply put that in some configuration file (using settings property tab of the project by example) and retrieve it from there.
Edit:
So, from your comment on this question, it looks like you have to seek the xl file in the executing folder.
There is a number of ways for achieving this, depending on your application use cases.
By example, check this question.

Since your project is not a Web one, I expect that you some sort of Output where build process generates an executable file, some assemblies etc. You can put Build action of your Excel as Content (more details here) and use this base path to retrieve it:
System.Reflection.Assembly.GetExecutingAssembly().Location
It is important to think in terms relative to your executable (or executing assembly to be more precise), since your output will have to run outside your development environment and your excel must still be accessible.
Also, getting the exact executing assembly might be tricky in some scenarios.

Related

Dynamically obtaining Json Filenames

I have a series of files in my program, which take user input and store them as a KeyValuePair some of them have names, most of them just have a numeric ID associated with them. This information needs to remain persistent across the application starting and stopping. I've tried several approaches but I can't get any of them to work quite right.
My approach was to simply have a Content folder, full of .json files I knew I could expect. When the program first launched, it reads the file using the Newtonsoft JSON Deserializer, and loads it into the appropriate place in memory as a List<KeyValuePair<int,string>. That all works fine, but getting the path to the File has proven exceedingly difficult.
I started with literals, but then realized I need to be able to have the program in any directory. So then I tried finding the absolute path of the file, given its relative name to the project. Still doesn't work because debugging and publish directories, as well as copy on compile stuff. As a minor issue, I also am annoyed that I still needed to use a string literal here.
SO, I resolved to make it a .resx file. This immediately failed, because you can't edit a .resx at runtime. So, referenced the external .json file from the .resx. The process of getting the URI or Path from the .resx proved excruciating if not impossible. I first tried
Assembly.GetExecutingAssembly().GetManifestResourceStream("MyJsonFile.Json") which I hoped would work but didn't.
So I had it print out String.Join(Assembly.GetExecutingAssembly().GetManifestResourceNames()) all I got out from the console wasMyNamespace.Properties.Resources.resources` and no indication of how to further extricate the location of any particular resource.
I even tried Assembly.GetExecutingAssembly().Location and couldn't do anything useful form there because it referred to my exe in the debug folder.
My last hope was an embeded content file, but I can't save those during the run time either. I can refer to the properly with URIs instead of literal strings, but I can't save them mid runtime, like I would need to in order to save on edit, or to even save from memory on close.
If anyone can give me clear information on how to extricate the URI or Path of a file in my solution without using literals, I would greatly appreciate it. Because I am getting nowhere with research I've done and the tools I have.
If you put it in your bin/debug folder, you do not need the path. You just need the names of the files.
Otherwise put the path in the .config file and then read it from there like this:
<appSettings>
<add key="Path" value="PathToFiles"/>
</appSettings>
Then get the setting like this:
using System.Configuration;
string path = ConfigurationManager.AppSettings["Path"];
Make sure to import

Default path in .NET (e.g. in Picturebox.Load())

When I run SomePicturebox.Load("Foo.bmp") and there is a Foo.bmp in the application's startup folder, it will load this image. However I have a case where the image is not loaded (when the application is started by an installer, namely).
Now I am wondering: Is there a default path that is searched by the framework when the path is not fully qualified? How can I show this path at runtime (to reveal why the image is not loaded in some cases)?
I tried looking at the Picturebox.ImageLocation property but this said just "Foo.bmp" without a path.
This is related to WinForms, .NET Framework 4.
Answers in both C# and VB.NET are very welcome.
In VB.NET
Dim directory as String = My.Application.Info.DirectoryPath
In C#
string directory = AppDomain.CurrentDomain.BaseDirectory;
I tested and AlexC was correct and I have updated this answer.
The best way to get the current value for the path is with System.IO.Directory.GetCurrentDirectory().
Rather than dealing with this ambiguity, though, it is better to make sure you fully qualify the path. To get paths on a system that can change, you should use the System.Environment.GetFolderPath call. For example, if you want the user's documents folder:
var path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
If you happen to be using an open file dialog the following is another call I often find helpful:
var fullPath = System.IO.Path.GetFullPath(selectedFile);
There are quite a few other routines in the System.IO.Path namespace that can help you with making sure that your file and path names are always fully qualified. Hope these help!
Note - My answer is in C#

Getting text file and is shiped with appliction

I have a file that I store some site links. Until now I used:
string path = Environment.CurrentDirectory + "/forumlinks.txt";
But I want to store the file in the release folder so I can change it and I know it will change permanently for the user.
So I changed to this:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"/forumlinks.txt";
But I get an exception:
System.IO.FileNotFoundException.
My question: is this the right way to get the file from the release folder? Should I rethink that and store him in a different place? If so I will be glad to hear about it.
I don't see the reason why you would need to call the
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
at all. This does the trick:
AppDomain.CurrentDomain.BaseDirectory
Hard coding a path to your code release folder is dangerous. What if you want to build in debug mode for some reason? What happens when you want to deploy your program?
A better choice would be to use the environment's application data folder. This will be different for each user, so it means that each user can have their own version of the file.
See this post for details of how to get the application data folder.
Well assuming the forward / is a typo.
If you've added the test file to your project, check it's properties, needs to be copy if newer / copy always to put it in bin\Debug or bin\Release, with the exe and dlls and other gubbins.
Why are you doing it this way, are you planing for something to change the file, without having to rebuild the application?
i made a mistake and found out that it was right to use this code:
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\fourmlinks.txt";
if you put the right name of the file, and still get an exception that mean that the file is not in the correct place.

How to determine whether an relative path points outside an given path

I have the following scenario (C#, WinForms). I have some kind of project file which is saved in some directory. The project file contains a reference to another file. This reference is relative from the place where the project file is saved.
Sample: The project file is saved under c:\projects\project.xyz. The other file is referenced as "\someotherdir\file.abc".
This works fine, but there may be the case someone tried to manipulate that relative path to something like "..\Windows\System32\file.abc". So there's a need to check whether the relative path points outside the path where the project is saved (it's a defined requirement, that all referenced files are inside the project path).
How to detect this scenario?
You could try using the following extension method:
public static bool IsChildOf(this string path, string parentPath)
{
return Path.GetFullPath(path).StartsWith(Path.GetFullPath(parentPath),
StringComparison.InvariantCultureIgnoreCase);
}
Not very pretty but I think it should work.
if (System.IO.Path.GetFullPath(path).IndexOf(projectPath, StringComparison.CurrentCultureIgnoreCase) == -1)
{
// naughty
}
Edited to be a good global citizen.
Windows has posix symlinks: ln -s c:\windows\system32\mshtml.dll c:\projects\project.xyz\innocent.txt. When your program opens c:\projects\project.xyz\innocent.txt you get c:\windows\system32\mshtml.dll. Does System.IO.Path.GetFullPath() work here?
POSIX also supports hardlinks. A file can have zero (when deleted), one, two, ten, one hundred filenames. And all are "The Filename", none more correct or less correct than any other.
Windows supports mounting folders into folders. Again, all names are correct.
You can solve this with filesystem permissions: Create a new user for your application. Give that user permissions to your project path. Do not give that user (or Everyone, or any groups the user is a member of) privileges to anything else in any filesystem. Let Microsoft's kernel team solve your problem for you.

Is it worth it to lookup the default application in the registry when opening a file from a C# application?

I'm building an application (a side project which is likely to enlist the help of the stackoverflow community on more than one occasion) which will need to open a variety of file types (i.e. open Word documents in Word, not natively in my application).
I've been playing with some code for looking up the default application for the file type in the registry and passing this to Process.Start(). There seem to be two issues with this approach:
1) The application name is quoted in some instances, and not in others.
2) Process.Start() requires that the application path and it's arguments are passed separately (i.e. Process.Start("notepad.exe", #"C:\myfile.txt"); rather than Process.Start(#"notepad.exe C:\myfile.txt");).
This means when I retrieve the path from the registry, I have to split it (after determining if I need to split on quotes or spaces) to determine what part is the application path and what parts are arguments, then pass those separately to Process.Start().
The alternative seems to be to just pass the filename, as in Process.Start(#"C:\myfile.txt"), but I think this only works if the application is in the Path environment variable.
Which way is better? In the case of the registry, is there a common solution for how to do the argument parsing?
Thanks for any and all help!
Update:
I guess the short answer is 'No.'
It seems like I was really going the overkill route, and that passing just the filename will work whenever there's an associated value in the registry. I.e. anything I find in the registry myself, Process.Start() already knows how to do.
I did discover that when I try this with a "new" filetype, I get a Win32Exception stating "No application is associated with the specified file for this operation." Fredrik Mörk mentions in a comment that this doesn't occur for him in Vista. What's the proper way to handle this?
If the extension is registered to be opened with a certain application, it doesn't need to be in the PATH in order to run.
The application does not need to be in the PATH if you only specify the filename. The following code worked fine for me:
System.Diagnostics.Process.Start(#"C:\Users\Dan\Desktop\minors.pdf");
You typically do not need to lookup the program for registered types, and the program does not typically need to be in the PATH environment variable. Usually the command in the registry contains the full path. This is how the command for .kml files (Google Earth) looks (in my computer):
C:\Program Files\Google\Google Earth\googleearth.exe "%1"
Given that, you can safely just use Process.Start together with the document file names. Should it be that the file type is not registered you will invoke the default Windows behaviour for this (asking you which program to use, and so on).

Categories

Resources