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.
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 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
I've been trying to learn how to handle saving normal .txt files in UWP, and have realized that it's quite locked down compared to WPF, especially in the sense of what folders you can access without requesting the user to select a location. I have searched for various ways this might be possible but found no working answer.
Question Description:
I basically would love to know if this is possible, and preferably a point in the direction where I can learn how exactly to do this.
Application settings page requires user to select folder where files are saved.
Application remembers this between launches (unsure if this is possible, but I can't require the user to select the folder on every launch)
Application saves files to the specified folder.
In my understanding, this should be possible, as the user is the one specifying the location via filepicker, but is it possible to have this work between launches so that the user wont be required to re-select the save folder?
I need to figure this out, as I would like my application to support selecting attached network drives, cloud storage folders, etc.
Any help is very much appreciated, and if there are any questions I will answer them to the best of my ability.
Fow this purpose there are two access lists designed: FutureAccessList and MostRecentlyUsedList. Once the user has picked up the folder with the picker, you add it to such list and receive a token, which you save for future purpose in LocalSettings:
ApplicationData.Current.LocalSettings.Values["MyFolder"] = StorageApplicationPermissions.FutureAccessList.Add(pickedFolder);
Then later, once you want to access that folder, you can do it like this:
StorageFolder folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(ApplicationData.Current.LocalSettings.Values["MyFolder"].ToString());
You can't save a StorageFolder or a path to it in settings, hence the UWP app needs permissions to access the folder. Using above access lists solves this problem.
I believe you want to save user settings and keep it somewhere so that next time when they launch the application, they can use the same settings.
Please check out this tutorial from Microsoft, which describes how to do exactly that.
https://msdn.microsoft.com/en-us/library/bb397750(v=vs.110).aspx
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've got a large folder on an offsite backup machine that gets populated with files by rsync (through deltacopy) every night (running windows xp) from the main work site. I've discovered some annoying folders that cannot be opened, or deleted, or even checked for file sizes. I get the such and such a folder is not accessible, access is denied message when I try to click on it in windows explorer. According to the windows explorer tooltip they are also "empty" and the properties of these folders say 0 bytes and 0 files.
I currently have a C# program that goes through every folder and file and tries to copy the whole backup directory to a dated backup-backup directory, which is how i discovered this problem in the first place. The regular System.IO library seems helpless against these blasted folders. Exceptions are thrown when I even try to access the folder path.
Does anyone have any clue how I could, say, on an access denied exception in my existing copy code, force the delete of these folders so rysnc can recreate the directory again and get the whole thing synced again?
First thing I think of when I see this is time to do a checkdisk. From the sounds of it, it feels more like a file system problem than something solvable the way you want to go about it.
Yes, try the awesome "Process Explorer" from Microsoft (formerly SysInternals).
Although it's for the processes in the windows filesystem, you could search for your folder in the explorer window & it will tell you who is locking it.
Once you release the process, your program would be able to delete the folder.
If that doesn't work, see if you can specify additional parameters to bruteforce the delete in your program.
It sounds like the filenames are either bad or contain characters that are invalid in Win32. Did you try to delete the directories with rd /r? Did you do a dir /x on them and try to delete the files/directories using their short names?
I would say that you first have to figure out why you can't delete the folders. Once you figure that out, you can write a program to fix it.
OK, so now that you know it's a permissions problem, the first step is to take ownership of the files (so you can set the permissions), then change the permissions so that you can delete the files.
Here's code to take ownership of a file:
WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
FileSecurity acl = File.GetAccessControl(filename);
acl.SetOwner(currentUser.User);
File.SetAccessControl(filename, security);
The trouble was that SYSTEM owned these files. I set deltacopy to run as administrator so that administrator would own the files deltacopy makes.
I guess windows is doing its job. The permissions are airtight. But if this happens again someday where I'd have to grab ownership from some other user to the current user (who has administrator permissions) how would I do that in code?
A question for another day I suppose. Thanks again everyone.