C# restore previous directory - c#

I currently have a FileHandler.cs class which does various things with a file. The default directory for C# running within VisualStudio is Project/bin/Debug or Project/bin/release depending on which you are running. As such in the constructor of my file class I do the following:
System.IO.Directory.SetCurrentDirectory("..\\..\\TextFiles");
to go from either bin or debug to the main folder where I have my TextFiles folder. The issue with this is the next time I create a FileHandlerthe working directory goes up 2 more levels where TextFiles doesn't exist.
How can I set the working directory to the default bin/debug again without using an absolute path?
There are several hacks I could use such as making it static or incremnting a counter for each FileHandler created and raising the current directory by 2 levels for each one past the first, but both those solutions are rather messy.
Thanks, Kalen

I would not rely on the default directory. It can change depending on how the application starts. Instead, you can try to detect location of the executable and use it to construct the data path. Something like this:
var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// or AppDomain.CurrentDomain.BaseDirectory, see http://stackoverflow.com/a/837501/3246555
var dataPath = Path.Combine(exePath, #"..\..\TextFiles");
//Directory.SetCurrentDirectory(dataPath);
Also, it might be better to avoid SetCurrentDirectory and construct the full file path instead:
var filePath = Path.Combile(dataPath, "MyFile.txt");

Related

How to define correct path for file in my ASP.NET application

I’m trying to save file to D:\folder1\folder2\file.txt using the following logic:
public void ChangeBackground(ChangeBackgroundDto dto)
{
var dir = Directory.GetCurrentDirectory();
File.WriteAllBytes("../../Images/Custom/BackgroundHome.png", dto.BGFileFormat);
}
However, when I do this, I recent an exception because I have root directory at C:\programfiles(x86)\llsExpress.
The exception message is: Could not find a part of the path 'C:\\Images\\Custom\\BackgroundHome.png'.
What path which will work for this even when I deploy the application?
First I'd suggest you to try to store your file in a relative path in the root folder if possible. This helps with security plus you'll know that all the files for your site are in the root folder.
If you really want to store files on a different drive, you cannot use relative paths to do this. So no .. in your paths. You'll have to use the absolute path. Store that somewhere in config or environment variables to avoid configuring file paths hard coded.
Finally please use code blocks to show code rather then screenshots on StackOverflow.
You can do this by putting the code as text between these chars ``. like this

File.Exist always return false

I know it's been asked a lot already, but I still can't get my code to work.
I built a little programm which lets you choose a product and asks for your information if you want to buy it. Every time the given information like name, address and so on... is saved in a single Excel file.
Now I want this file to be created if it doesn't already exists. It works to create one, and overwrite it. But if it exists, File.Exist will return a false anyway and overwrite the entire file with a new blank. It get's created to [user]\Documents folder.
My idea to check if the file already exists was this:
if (!File.Exists(#"C:\Bestellungen.xlsx"))
{
CreateNewHistory(); // Method which creates the file in correct format
}
WriteData(); // Method to write given information to correct cells
The method for creating the file is simply:
private void CreateNewHistory()
{
Excel excel = new Excel();
excel.CreateNewFile();
excel.SaveAs(#"Bestellungen.xlsx");
...
// some cells get writte here, just for format
...
excel.Close();
}
"Bestellungen" is German for "orders"... ;)
I suppose it has something to do with the way I pass the path into File.Exist but I am just clueless. I tried to copy the file into the bin\debug folder of my project. If it's there it works perfectly, but i really would like to know how i can find the file in the documents folder. I already tried put the absolute path, but it's always returning false.
If you need more information about the code let me know, I'm really new to c# or coding basically.
You're saving the file using a relative path. The file will be saved in the program's working directory. Using C:\ will never work. In fact, you can't even write to the root folder without elevated privileges. Program Files is another folder you can't (and shouldn't even try) to save into, since 1995.
Older Windows versions would just throw an exception. Some developers would try to force permissions instead of fix their bugs, so newer versions redirect inappropriate writes to eg Documents or APPDATA. I suspect you run your program from Program Files and the OS redirected the file save operation to Documents.
You should use an absolute path to save files in the correct folder. User documents go to Documents, application files go to APPDATA etc. You can get the absolute path to each of those locations with Environment.GetFolderPath, and one of the SpecialFolder values like Desktop or MyDocuments eg :
var docFolder=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath=Path.Combine(docFolder,"Bestellungen.xlsx");
excel.SaveAs(filePath);
And retrieve it the same way:
var docFolder=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath=Path.Combine(docFolder,"Bestellungen.xlsx");
if (!File.Exists(filePath))
...
The SpecialFolder enumeration explains the purpose of the various folders:
MyDocuments contains document files for the current user,
Desktop points to the current user's desktop
ApplicationData and LocalApplicatinoData contain application-specific files used by the current user, like logs and settings etc.
CommonDocuments, CommonDesktop, CommonApplicationDatacontain files used by all users on a computer
Use the Document folder to save your file.
Get the User Document Folder
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Set the Filename
string file="Bestellungen.xlsx";
Finally, generate your actual path
String absolutePath = System.IO.Path.Combine(path , file);
its throw a exception due to permission issue
please change directory or give proper permission

C# - Relative path of class

Trying to get relative path of config file, which is next to a class in core project, and also trying to avoid hardcoded relative paths (i.e. "../../../seleniumconfig.json")
This is my project structure,
Awesome.Core (library project)
Selenium (folder)
ZSelenium.cs
seleniumconfig.json (want it here so only powerusers can reach to this file)
Awesome.OtherProject1 (calling project, references Awesome.Core)
Program.cs
Awesome.OtherProject2 (another calling project, references Awesome.Core)
Program.cs
Program.cs (in Awesome.OtherProject1)
using (var scope = Container.BeginLifetimeScope())
{
var selenium = scope.Resolve<ZSelenium>();
...
}
ZSelenium.cs
var rootDir = new DirectoryInfo(Environment.CurrentDirectory);
// "/users/myuser/Documents/MyProject/AwesomeProject.OtherProject"
I can construct my relative path from rootDir variable, but there will be a lot of hardcoded ../../.. stuff which I would like to avoid. Also, if I call ZSelenium.cs from another project, the relative path might change.
Does anyone know a better way to get the path of ZSelenium.cs within the core project?
Configurations files do not belong into the Programm folder, ever. We did kind of do it anyway in the Windows 98 times, but it was frowned upon back then. Since XP is it not reliably possible anymore to write such a configuration file. The Programm folders is protected. Most users can only read them, not write them for security reasons. And that includes any programms started by that user too.
If you want to store user or system specific settings, that is what the special folders are there for. Their one defining purpose is that whatever user runs your programm, should have read (and likely write) access to his own and all shared folders.
You may be able to add a "default configuration" to the Programm directory to use as pattern for new users. But even for that there is a existing structure (the default user folder) so you can leave placing the template to the Setup.

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.

Change pictureBox.Image with c# = FileNotFoundException

i have a small app in C# winform. It work great but i don't understand how to change the image of a picture box in code :
i have this directory for my image :
myProjectDirectory/bin/Pics/myImage.jpg
and this code give me an FileNotFoundException :
this.imgInvader.Image = Image.FromFile("../Pics/invader2.jpg");
i don't understand because i see on stackoverflow that FromFile method begin at bin/Release. So a ../Pics/myImage.jpg should work no ?
Thx
Use the relative path of the image.
this.imgInvader.Image = Image.FromFile(#"bin\Pics\invader2.jpg");
Here give the path from the location where your code behind file is located. Suppose if your file is in root directory and if your images are in bin/Pics/ folder then the above code works. It automatically gets the path related to the location the program is running from.
Trying to reference image files that are outside the executable output directory is incredibly fragile. There are lots of ways it can go wrong (unfortunately, there's not enough context in your question for anyone to know exactly which of these ways is your specific problem).
If you must use files on disk to store your image resources, then they should be copied into the build output directory (i.e. "Release") and referenced there. Add the file to your Visual Studio project, select it, and in the properties window, set the "Build Action" value to "Content". If the file is in a folder under the project, then it will also be copied to a folder of the same name in the output directory.
If you do use files on disk, the other thing to make sure you do is find the executable's directory (e.g. via Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)) and then combine that with your expected relative path (e.g. just the file name, or the file name under whatever folder/subdirectory you gave it in the project, if you did) using the Path.Combine() method, and then using that absolute file name as the source. Otherwise, your code can be confused by changes in the current directory made elsewhere in your program (basically, don't ever rely on the current directory…global state like that is too easy to get mixed up, once you get into the habit of using it).
For example:
string exeDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string imageFileName = Path.Combine(exeDirectory, "invader2.jpg");
Now, all that said, IMHO it is probably a better idea to add your images as resources in the executable itself, and then reference them from the Properties.Resources class. Then the images are always with the executable, because they are in the same file. The code is a lot easier too, because you're just referencing properties in the Resources class that return the actual Image objects you need.
As the previous comment stated, using resources outside of your exe is not advised however you can still do this by using the Path.GetDirectoryName Method.
I am left to question why your resources are based outside of your exe, why not embed it into your resources located in properties > resources.resx and simply call it with imgInvader.Image = Properties.Resources.FileNamehere; it is a lot safer than trusting the external environment.

Categories

Resources