I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.
i.e.
This is what I have at the moment, which currently works, but has the C:\ in the beginning.
StreamWriter sw = new StreamWriter(#"C:\Test folder\output\test.txt");
I really want to write the file to the output folder, but with out having to have C:\ in the front.
I have tried the following, but my program just hangs (doesn't write the file out):
(#"\\Test folder\output\test.txt");
(#".\Test folder\output\test.txt");
("//Test folder//output//test.txt");
("./Test folder//output//test.txt");
Is there anyway I could do this?
Thanks.
Thanks for helping guys.
A colleague of mine chipped in and helped as well, but #Kami helped a lot too.
It is now working when I have:
string path = string.Concat(Environment.CurrentDirectory, #"\Output\test.txt");
As he said: "The CurrentDirectory is where the program is run from.
I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.
If you need to write to specific drive or current drive you can do the following
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + #"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);
If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.
You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..
I don't get clearly what you want from this question , hope this get it..
A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:
string exeRuntimeDirectory =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string subDirectory =
System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
// Output directory does not exist, so create it.
System.IO.Directory.CreateDirectory(subDirectory);
}
This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.
It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.
Related
get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
I am trying to upload a file with the sendkeys function on the inputid.
I am currently using the path C:\Users\myusername\Documents\seleniumsolution\Utils\Dir\Dir1\Dir2\Dir3\UploadFolder\example.jpg
I see the file in my solution. But I dont want to give to complete path but only the filename and that selenium finds the path itself. Otherwise I will be the only one that can use this testcase.
I tried with:
var file = Path.Combine(Directory.GetCurrentDirectory(), url);
And tried with:
string documents = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"UploadFolder");
Both of them dont give me the required result.
Hope that you guys can help me out.
You might need to travel on the folders tree to get to the file
AppDomain.CurrentDomain.BaseDirectory
will get you in the bin\debug folder. From there you can use parent to move up to the file location. For example (might need some tweaking)
string solutionParentDirectory = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName;
string file = Path.Combine(solutionParentDirectory, #"UploadFolder\example.jpg");
You can also try
string file = Path.GetFullPath("example.jpg");
The program I am writing is a stock inventory system.
So the PC I wrote the program on can locate the files and folders to update on the PC as necessary as the path is valid.
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts"))
{
Directory.CreateDirectory(path);
}
var fileName = #"c:\Users\ThisPC\Documents\Stock Documents\Tyre_File.xml";
This line is also used when I am updating quantities when an order is taken.
So obviously when I run this program in visual studio on another PC this path isn't recognized.
Is there a way that I can add a pointer to create and store my folder and documents in the My Documents on any pc the program loads in?
UPDATE-------------------------------------------------------
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts"))
{
Directory.CreateDirectory(path);
}
This is the only one it wont work for, it creates a folder within a folder when the form is loaded, but your method doesnt work for that?
I believe that
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
is what you are looking for
You want the environment variable for MyDocuments, which will be unique for each user/computer.
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
I want to read a file path from the following structure
The Structure is like : AssemblyName -> MyFiles (Folder) -> Text.txt
Here I want to get the path of the Text.txt. Please help
I think what you're looking for is a file embedded in the assembly. Check out this question. The first answer explains how to set up an embedded file, as well as how to get it from code.
You can do
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyDirectory = Path.GetDirectoryName(assemblyPath);
string textPath = Path.Combine(assemblyDirectory, "MyFiles", "Test.txt");
string text = File.ReadAllText(textPath);
...just to split it up some...but you could write it all in one line needless to say...
alternatively, if your Environment.CurrentDirectory is already set to the directory of your executing assembly's location, you could just do
File.ReadAllText(Path.Combine("MyFiles", "Text.txt"));
Jeff has covered how you get the path, wrt your comment on his answer is the file you want to open actually included in your project output?
Under the properties pane for the relevant file look at the Copy to Output Directory option - it generally defaults to Do not copy. You will want to set it to Copy Always or Copy if Newer if you want to include a file in the output directory with your compiled program.
As a general note you should always wrap any IO in an appropriate try catch block or use the static File.Exists(path) method to check whether a file exists
I have a program that "greps" out various directory paths from a log text file and prints various results according to the word.
Examples of Directory paths:
C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk
C:/Documents and Settings/All Users/Start Menu/Programs/AccessData
C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier
Therefore how can I grep out the file or folder name after the last "/"? This is to help the program to identify between files and folder. Please do take note of the multiple "." and white spaces found within a directory paths. etc "Imager.exe:Zone.Identifier". Therefore it is difficult to use if(!name.contains()".")
Etc. How to get the "AccessData FTK Imager.lnk" or "AccessData" or "AccessData FTK Imager.exe:Zone.Identifier" from the path STRING?!
May someone please advise on the methods or codes to solve this problem? Thanks!
The codes:
if (!token[7].Contains("."))
{
Console.WriteLine("The path is a folder?");
Console.WriteLine(token[7]);
Console.WriteLine(actions);
MacActions(actions);
x = 1;
}
Use the Path class when working with file paths, and use the File and Directory class when working with actual files and folders.
string str1=#"C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string str2=#"C:/Documents and Settings/All Users/Start Menu/Programs/AccessData";
string str3=#"C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier";
Console.WriteLine(Path.GetFileName(str1));
Console.WriteLine(Path.GetFileName(str2));
Console.WriteLine(Path.GetFileName(str3));
outputs:
AccessData FTK Imager.lnk
AccessData
Zone.Identifier <-- it chokes here because of the :
This class operates on strings, as I do not have those particular files and/or folders on my system. Also it's impossible to determine whether AccessData is meant to be a folder or a file without an extension.
I could use some common sense and declare everything with an extension to be a file (Path.GetFileExtension can be used here) and everything else to be a folder.
Or I could just check it the string in question is indeed a file or a folder on my machine using (File.Exists and Directory.Exists respectively).
if (File.Exists(str2))
Console.WriteLine("It's a file");
else if (Directory.Exists(str2))
Console.WriteLine("It's a folder");
else
Console.WriteLine("It's not a real file or folder");
Use Path.GetFileName.
The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty.
This is to help the program to identify between files and folder
There is no way to determine is a path represents a file or folder, unless you access the actual file system. A directory name like 'Foo.exe' would be perfectly valid, and a file with no extension ('Foobar') would be valid too.
how about tokenized it with "/" like what you're doing ... and then you'll know that the last token is the file, and whatever before it is the path.
You can simply split the whole string by /
e.g.:
string a="C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string[] words=a.split('/');
int len=words.length;
so now words[len] returns the data after last slash(/)..
I hope you understand...
I guess you only have a string that represents the name of the file, if that is the case you can't really be sure. It's totally ok to have a folder namen something like Folder.doc. So if you don't have access to the actual file system it is hard to check. You can get close though using regular expression like:
(.*\\)(.+)(\..*)
Try it on: http://www.regexplanet.com/simple/index.html
If you get any output in group number 3 it's likely that it is a file and not a folder. If you don't get some output try this direct after:
(.*\\)(.+)(\..*)?
That will give you the folder in group 2.