c# asp.net web api file existance not found using namespace - c#

I hope I'm doing something wrong because to me at this moment it looks like what I'm doing is correct. First off I want to open a file using the name space.
Lets say I have this string:
string resource = "Middelware.DataResources.dba.Queries.getTest.sql"
Then I'm trying to open it using:
var stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)
But it doesn't work unfortunately. So I have been using this as a test case:
if (File.Exists(#"C:\text.txt"))
But for some reason it keeps returning false. I played around abit as well like using: "C:\\text.txt". But nothing happens.
I'm using visual studio 2017. And the class this is happening in is static.
So my questions:
Why cant file.exist seem to validate the test file exists?
Why is
var stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource) not working, given that the namespace should be correct?
Hope some can help me with this silly problem.
Kind regards

You are not providing too much information so I'm guessing.
Read from file
From File.Exists method reference, the returned value can be:
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false.
This method also returns false if path is null, an invalid path, or a zero-length string.
If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.
You have already excluded some cases, so you should check whether the application has proper read permissions for the target file or its parent directory.
Read from assembly
Issues with resource streams are often related to:
Wrong resource name. Can be the upper/lower case, or an additional string put as prefix by Visual Studio compiler.
Resource not actually compiled in assembly
You can list all available resources in your assembly with:
Assembly.GetExecutingAssembly().GetManifestResourceNames()

Answer question 1: I had a typo..
Question 2 Is given in the comments. Let me quote:
Have you changed the type of the sql script to 'Embedded Resource' in the IDE? – Matt 3 mins ago

Related

Why Path.GetFullPath returns the address with extra "bin/Debug/netcoreapp3.0"?

I have a file on mac which is at /Users/Bsh/Desktop/myProgram/myFile.txt when I use this address instead of Path.GetFullPath("myFile.txt") in the C# program, the file is found by the program but when I use Path.GetFullPath("myFile.txt") the program does not find the file. To find out what Path.GetFullPath returns, I used Console.WriteLine(Path.GetFullPath("myFile.txt")); and the output was /Users/Bsh/Desktop/myProgram/bin/Debug/netcoreapp3.0/myFile.txt.
Why is there an extra part: bin/Debug/netcoreapp3.0? And how to resolve the issue?
Thanks.
The first step you should take when a library method is not working as expected, is Read The Documentation.
In particular, you should be paying special attention to this part:
This method uses the current directory and current volume information to fully qualify path. If you specify a file name only in path, GetFullPath returns the fully qualified path of the current directory.
The answer to your question seems rather obvious.

Visual Studio c# relative path, program searching two paths even when it finds the correct one

I'm developing a desktop application for windows using visual studio. I'm programming in C# using WPF for UI.
I've googled looking for an answer, but haven't found any. Most likely because I don't exactly know what the actual problem is.
I've run into a problem where I'm trying to access a file in the folder resources
(C:\Users\MyName\Projects\MyProject\ProjectName\resources\xml\test.xml)
Using this code:
XElement xmlFromFile = XElement.Load(#"..\..\resources\xml\test.xml");
The issue is that the file is found and the xml can be accessed through the xmlFromFile variable, BUT the program also searches
D:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\resources\xml\test.xml
The same also happens if I try this:
static string codePath = Directory.GetParent(Directory.GetParent(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)).FullName).FullName;
FileLog log = new FileLog(codePath + "\\logs\\log.txt");
log.Log("Test")
Where codePath refers to the directory where the class files are, FileLog is a class that simply logs to a file using File.AppendAllText(path, string).
This piece of code gives the same error, but the path is instead:
C:\Users\MyName\AppData\Local\Microsoft\VisualStudio\15.0_919b9cb1\Designer\ShadowCache\logs\log.txt
But this one also writes the input string(test) to the correct file in the correct place. So why is this a problem if it works? While it works correctly here, the issue is that WPF does not give me a preview of the UI like it usually does, there's probably also other issues, but none that I am aware of. The preview simply states: Cannot create an instance of "Home". Where Home is a WPF UserControl.
So my question is: How to I fix the code so that the program does not search in both places(if indeed that's what it does)?.
What is happening here I believe is not that the program is not searching multiple places for a file, but the assembly from which the relative file search is being done is being loaded from different places. .NET has a fascinating and little understood mechanism for finding an assembly and loading it which is described in this document: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx
So I think what is happening is that you are examining this behavior in different contexts (i.e. using the debugger, in the designer, etc.) and the assembly that is being used is loaded from a different place and therefore evaluates the relative file path differently.
So if I am right, then you are chasing a shadow. This is an artifact of behavior on your development machine which will disappear once the application is deployed and there is only one place for .NET to find the release assembly.

Get FilePath for my excel file with sheetname

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.

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#

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