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
Related
I need to make a program that reads the columns of an excel. But for that, I need to get the path (directory) of this excel. What prevents me from doing this, is that I didn't want to leave my local directory fixed, because if someone downloads the file on another machine, they will need to change the path.
You asked How to get directory of an xls file C#.
As others have pointed out, the file needs to be in a known location and one way to do that is to add the Excel file to your solution and mark it as Content, specifying that it should be copied to the output directory. The image below shows how to set these properties.
You also seem to be looking for a robust way to make this happen when you deploy the app for other users. For this, you will need a strategy for making an .msi or .msix that will place this file where it needs to be. But to answer your basic question the way you asked it the path in this case can be obtained in this manner. This code will get the path and open the Excel file.
// Get the path and open the Excel file
static void Main(string[] args)
{
var path =
Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Microsoft Excel Worksheet.xlsx");
Console.WriteLine(path);
System.Diagnostics.Process.Start("explorer.exe", path);
}
I should mention that a file in the executing directory can be read but not written (without elevated permissions). If the file is user data then refer to the answer that uses an Environment variable:
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
You have two options:
If you don't want to your excel files to be stored in your application's directory, you can simply put things in the root of your C: partition. Every windows device is gonna have the C: partition. As the user Lee Taylor has pointed out, it turns out you can have a windows device without the C: partition, although uncommon
If you don't mind having your excel files stored in your application's directory, you can get the relative path of your application's directory throughPath.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
There are other ways but I believe these are the simplest and easiest to do.
If you just need to dynamically get the path to a file that is in the same project directory, then the following code works for me -
string filePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\excel\\Prices.xlsx";
where "\excel" is the folder in my project and "\Prices.xlsx" the file in the project
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
I'm a little stuck, as for this moment i don't have any code only an idea.
I was thinking to make a program in asp.net to list files within a location.
The file will probably be releases for programs and mods for gaming and stuff.
But i have searched everywhere to get files in a location. I could use system.io.fileinfo to list files in a directory.
But how to I get a Directory not in the solution but somehwere on the hard drive or even external storage server? The location i prefer not to be hard coded but selected by the user? any toughts on how a user can select a 'location' ?
In a console application, you could be doing something like this :
Ask for the path from the user with a readline.
Check if the path is correct / exists. (if not you could create it or display an error, also it could be a path with a file, you need to check if the path is to a directory or to a file)
Do the display of the files inside of the directory as intended.
We need more precisions if you want a better answer.
I´m writing a C# Program which record all changes in a UNC Path.
I use the File-System-Watcher in c# to record all changes in my file \D/X/Y(UNC path).
It works very good but now my question: how is it possible to record the Client which change/delete etc. the file ?
EDIT: The UNC Path will be seen in the whole network and I want to record which user change/delete etc a file in the UNC Path (Every one in the network can change the files). Each edit will be saved in real time in a .txt file. So that i can see :
who:PC2 what:change file:X
who:PC1 what:delet file:Y
Use the following code to get the credentials of the user that is logged in
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
If you put this wherever the code is for the file change/deletion is, this should work.
Take a look at this
You basically need to create an auditing process for this, I'm not aware there is a built in way to find information such as who last changed a file.
I'm not sure what you mean by "who" is claiming or modifying a file. As far as I am aware, you can view properties of a file (if you have permissions to view the permissions), the current user (see Jacooobley's answer), and the process that is locking the file.
I don't believe you can see the user who has last effected the file.
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.