i'm currently doing an assignment at university and i'm struggling on a specific task
After displaying a file listing i need to prompt the user to enter the number of a file to get more details on that file. The user can then enter the number 0 to skip this step. The extra details shown should be:
File: notepad.exe
Full file name: C:\Windows\notepad.exe
File size: 93536 bytes
Created: 14/07/2009 12:54:24
Last accessed: 10/08/2009 15:21:05
im using C# im wondering if anyone knows how to guide me on the right step? thankyou
For general file information, like size and creation and modification times, use the FileInfo class.
FileInfo f = new FileInfo(#"C:\Windows\Notepad.exe");
long size = f.Length;
DateTime creation = f.CreationTime;
DateTime modification = f.LastWriteTime;
string name = f.Name; //returns "Notepad.exe"
//etc...
Alternatively, for getting a filename from a full path, use the Path class.
string fName = Path.GetFilename(#"C:\Windows\Notepad.exe"); //returns "Notepad.exe"
I'll leave formatting the info string to you.
Be advised that FileInfo depends on the existence of the file, while the Path methods only deal with string manipulation. The file does not need to exist.
Related
This question already has answers here:
Given a filesystem path, is there a shorter way to extract the filename without its extension?
(10 answers)
Closed 5 years ago.
I have searched everywhere to find this answer but still can't find it.
I have a file in my Documents folder. I create and append a file with the same content in another folder. (Let's say Downloads). How do I give the new file the same name as the old file?
I just need help with naming the new file the same as the old. I already have it appending and sending to another folder. I'm using StreamReader to read the old file and StreamWriter to create the new file. I dont want to hard code a path to rename it, because there may be multiple files that I need to read.
It's not clear exactly what you're asking for, but I'll take a stab at it.
If you're using something like the File.Copy() method, then you just have to use the full file path for both the source and destination. If you're passing a string value with the full path to the file, you can get just the file name using Path.GetFileName()
Here's an example based on my loose guesstimation of your question:
var filename = Path.GetFileName(sourcePath);
var newPath = $"{destinationFolderPath}\\{filename}";
File.Copy(sourcePath, newPath);
Additional Reading: https://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx
There is a static function Path.GetFilename, which returns a file name contained in a path passed as the argument:
var filename = Path.GetFilename(#"c:\file.txt"); // filename = "file.txt"
Path also contains other useful funtions, such as GetFilenameWithoutExtension.
Use Path.GetFileName i.e.
// The path you want to copy the filename of.
// C:/Users/<username>/Documents/<some file> in your case.
var srcPath = //...
// The directory you want to copy to.
// C:/Users/<username>/Downloads in your case.
var destDir = //...
// Different directory, same filename.
var destPath = Path.Combine(destDir, Path.GetFileName(srcPath));
In my application there is a option for where user creates a simple txt file containing some data. I would like to name the file in sequential order like ST1, ST2.... This sequence will be remain same for all users. if user1 creates a file system should name the file ST100 and then if user2 creates a file then system should name the file ST101.
I cant use the application scope as it is ready only and cant be changed at run time where as the user scope will only impact individual user not across the whole application.
I was wondering is there any other solution to achieve this apart from using database table and tacking sequence.
Thanks
You could use a loop and File.Exists:
var dir = #"C:\SampleFolder";
int number = 100; // you want to start at 100
string fileName = String.Format("ST{0}.txt", number.ToString("D3"));
while(File.Exists(Path.Combine(dir, fileName)))
fileName = String.Format("ST{0}.txt", (++number).ToString("D3"));
Finally you will have a new file-name and you get the correct path:
string path = Path.Combine(dir, fileName);
if your application is always on, you can use a global variable for the entire system with the numeric value of the next entry.
if not, you can use a text file as a database with the current number of the file; The problem with this solution is the synchronization, if two users doing the same operation at the same time can give you problems, so it is best to use a database.
I hope it helps you
http://pastebin.com/DgpMx3Sx
Currently i have this, i need to find a way to make it so that as opposed to writing out the directory of the txt files, i want it to create them in the same location as the exe and access them.
basically i want to change these lines
string location = #"C:\Users\Ryan\Desktop\chaz\log.txt";
string location2 = #"C:\Users\Ryan\Desktop\chaz\loot.txt";
to something that can be moved around your computer without fear of it not working.
If you're saving the files in the same path as the executable file then you can get the directory using:
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Normally you wouldn't do that, mostly because the install path will be found in the Program Files folders, which require Administrative level access to be modified. You would want to store it in the Application Data folder. That way it is hidden, but commonly accessible through all the users.
You could accomplish such a feat by:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, #"NameOfApplication");
With those first two lines you'll always have the proper path to a globally accessible location for the application.
Then when you do something you would simply combine the fullPath and the name of the file you attempt to manipulate with FileStream or StreamWriter.
If structured correctly it could be as simple as:
private static void WriteToLog(string file)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, #"NameOfApplication");
// Validation Code should you need it.
var log = Path.Combine(fullPath, file);
using(StreamWriter writer = new StreamWriter(log))
{
// Data
}
}
You could obviously structure or make it better, this is just to provide an example. Hopefully this points you in the right direction, without more specifics then I can't be more help.
But this is how you can access data in a common area and write out to the file of your choice.
I wrote a simple console tool that reads a file and then writes something out. I intend to just drag and drop files and then out pops the output in the same directory as the input file.
All of the testing works, and when I call it from command-line, everything comes out as expected. However, when I tried dragging and dropping it in explorer, no files were created.
I did a search through the system and found that they were all dumped at Documents and Settings under my user folder, and when I printed out the full path that's what it said.
Which is weird. Wouldn't Path.GetFullPath return the absolute path of the input file? Instead it looks like it just combined that user directory path to the input's filename.
EDIT: here's the code. I feel like I've made a logic error somewhere but can't seem to see it.
filename = System.IO.Path.GetFileName(args[i]);
abspath = Path.GetFullPath(filename);
dirpath = Path.GetDirectoryName(abspath);
....
Console.WriteLine(dirpath);
Path.GetFullPath should return the absolute path of the path string you pass in.
Path.GetFileName(string path) only returns the filename and extension of the file you pass in. For example, System.IO.Path.GetFileName("C:\SomeDirectory\Test.txt"); would just return "Test.txt". You'll want to use the Path.GetDirectoryName to get the path of your input file, like so:
string inputDirectory = System.IO.Path.GetDirectoryName(args[i]);
Alternately, you can use the FileInfo class to retrieve a bunch more information about your input file. For example:
// Assuming args[i] = "C:\SomeDirectory\Test.txt"
FileInfo inputFile = new FileInfo(args[i]);
string inputDirectory = inputFile.DirectoryName; // "C:\SomeDirectory"
string inputFileName = inputFile.Name; // "Test.txt"
string fullInputFile = inputFile.FullName; // "C:\SomeDirectory\Test.txt"
I use coded UI to run test and get the test result file named like qian_machinename 2011-12-21 14_26_10. I want to read the file and send a test report. My question is how can I get the file time every time I run the tests?
TestContext has 3 properties which you can use
1. TestDir
2. TestDeploymentDir
3. TestResultsDirectory.
You can use these properties to navigate to the folder you are interested in and then get the result file for your processing.
QianLi,
Perhaps you can get the proper output file by using a known pre-fix on the test output filename.
In Visual Studio navigate Test->Edit Test Settings->(Select your active .testsettings)->General
In the prompt that displays you will see an area for naming scheme. By default this is set to name your output file "USER#MACHINE DATE TIME". You can create a user defined scheme and use that to locate the file i.e. store "MyTestOuput" as a pre-fix and then later in code you can examine the file creation date/time if necessary to verify you have the correct output.
Use something Like :
FileName=
testContext.ResultsDirectory + "\" + testContext.TestName.ToString()+".extension"
Testname should be the name of the testMethod Like "T1".
Extension could be any valid file type e.g. .xml etc.
[TestCleanup()]
public void MyTestCleanup()
{
string nomfichiersource = "UITestActionLog.html";
string nomTest = TestContext.TestName.ToString();
string sourcefile = System.IO.Path.Combine(TestContext.TestResultsDirectory, nomfichiersource);
string destfile = System.IO.Path.Combine(#"X:\Temp", nomTest + ".html");
System.IO.File.Copy(sourcefile, destfile);
}