What am I doing wrong in the following code?
public string ReadFromFile(string text)
{
string toReturn = "";
System.IO.FileStream stream = new System.IO.FileStream(text, System.IO.FileMode.Open);
System.IO.StreamReader reader = new System.IO.StreamReader(text);
toReturn = reader.ReadToEnd();
stream.Close();
return toReturn;
}
I put a text.txt file inside my bin\Debug folder and for some reason, each time when I enter this file name ("text.txt") I am getting an exception of System.IO.FileNotFoundException.
It is not safe to assume that the current working directory is identical to the directory in which your binary is residing. You can usually use code like the following to refer to the directory of your application:
string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string filename = System.IO.Path.Combine(applicationDirectory, text);
This may or may not be a solution for your given problem. On a sidenote, text is not really a decent variable name for a filename.
If I want to open a file that is always in a folder relative to the application's startup path, I use:
Application.StartupPath
to simply get the startuppath, then I append the rest of the path (subfolders and or file name).
On a side note: in real life (i.e. in the end user's configuration) the location of a file you need to read is seldom relative to the applications startup path. Applications are usually installed in the Program Files folder, application data is stored elsewhere.
File.ReadAllText(path) does the same thing as your code. I would suggest using rooted path like "c:......\text.txt" instead of the relative path. The current directory is not necessarily set to your app's home directory.
You can use Process Monitor (successor to FileMon) to find out exactly what file your application tries to read.
My suggestions:
public string ReadFromFile(string fileName)
{
using(System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
using(System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
return = reader.ReadToEnd();
}
}
or even
string text = File.OpenText(fileName).ReadToEnd();
You can also check is file exists:
if(File.Exists(fileName))
{
// do something...
}
At last - maybe your text.txt file is open by other process and it can't be read at this moment.
Related
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'm working on a project for a class. What I have to do is export parsed instructions to a file. Microsoft has this example which explains how to write to a file:
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
I'm fine with that part, but is there a way to write the file to the current project's environment/location? I'd like to do that instead of hard coding a specific path (i.e. "C:\\test.txt").
Yes, just use a relative path. If you use #".\test.txt" ( btw the # just says I'm doing a string literal, it removes the need for the escape character so you could also do ".\\test.txt" and it would write to the same place) it will write the file to the current working directory which in most cases is the folder containing your program.
You can use Assembly.GetExecutingAssembly().Location to get the path of your main assembly (.exe). Do note that if that path is inside a protected folder (for example Program Files) you won't be able to write there unless the user is an administrator - don't rely on this.
Here is sample code:
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");
This question / answer shows how to get the user's profile folder where you'll have write access. Alternatively, you can use the user's My Documents folder to save files - again, you're guaranteed to have access to it. You can get that path by calling
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If you want to get the current folder location of your program use this code :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text
Full code to write the data to the file :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
string fileName = Path.Combine(path, "test.txt");
if (!File.Exists(fileName))
{
// Create the file.
using (FileStream fs = File.Create(fileName))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
Most of the examples shows how to read text file from exact location (f.e. "C:\Users\Owner\Documents\test1.txt"). But, how to read text files without writing full path, so my code would work when copied to other computers. With visual studio I added 2 text files to project (console project) and don't know best way to read those files. Hope I described my problem clearly. Maybe I needed to add those txt files differentely (like directly to same folder as .exe file)?
You could use Directory.GetCurrentDirectory:
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");
Which will look for the file fileName.txt in the current directory of the application.
If your application is a web service, Directory.CurrentDirectory doesn't work.
Use System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "yourFileName.txt")) instead.
When you provide a path, it can be absolute/rooted, or relative. If you provide a relative path, it will be resolved by taking the working directory of the running process.
Example:
string text = File.ReadAllText("Some\\Path.txt"); // relative path
The above code has the same effect as the following:
string text = File.ReadAllText(
Path.Combine(Environment.CurrentDirectory, "Some\\Path.txt"));
If you have files that are always going to be in the same location relative to your application, just include a relative path to them, and they should resolve correctly on different computers.
You need to decide which directory you want the file to be relative to. Once you have done that, you construct the full path like this:
string fullPathToFile = Path.Combine(dir, fileName);
If you don't supply the base directory dir then you will be at the total mercy of whatever happens to the working directory of your process. That is something that can be out of your control. For example, shortcuts to your application may specify it. Using file dialogs can change it.
For a console application it is reasonable to use relative files directly because console applications are designed so that the working directory is a critical input and is a well-defined part of the execution environment. However, for a GUI app that is not the case which is why I recommend you explicitly convert your relative file name to a full absolute path using some well-defined base directory.
Now, since you have a console application, it is reasonable for you to use a relative path, provided that the expectation is that the files in question will be located in the working directory. But it would be very common for that not to be the case. Normally the working directory is used to specify where the user's input and output files are to be stored. It does not typically point to the location where the program's files are.
One final option is that you don't attempt to deploy these program files as external text files. Perhaps a better option is to link them to the executable as resources. That way they are bound up with the executable and you can completely side-step this issue.
You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.
So it could relate to the current directory (get it from Directory.GetCurrentDirectory()) or to the application executable path (eg. Application.ExecutablePath comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath() with one element of the Environment.SpecialFolder enumeration).
Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!
In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.
As your project is a console project you can pass the path to the text files that you want to read via the string[] args
static void Main(string[] args)
{
}
Within Main you can check if arguments are passed
if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}
Extract an argument
string fileToRead = args[0];
Nearly all languages support the concept of argument passing and follow similar patterns to C#.
For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx
This will load a file in working directory:
static void Main(string[] args)
{
string fileName = System.IO.Path.GetFullPath(Directory.GetCurrentDirectory() + #"\Yourfile.txt");
Console.WriteLine("Your file content is:");
using (StreamReader sr = File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
Console.ReadKey();
}
If your using console you can also do this.It will prompt the user to write the path of the file(including filename with extension).
static void Main(string[] args)
{
Console.WriteLine("****please enter path to your file****");
Console.Write("Path: ");
string pth = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Your file content is:");
using (StreamReader sr = File.OpenText(pth))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
Console.ReadKey();
}
If you use winforms for example try this simple example:
private void button1_Click(object sender, EventArgs e)
{
string pth = "";
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
pth = ofd.FileName;
textBox1.Text = File.ReadAllText(pth);
}
}
There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using
Assembly.GetExecutingAssembly().Location
and then use Path class to get a directory name.
Be careful about the leading \\
string path2 = "\\folderName\\fileName.json";
string text = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), path2));
If path2 does not include a root (for example, if path2 does not start with a separator character \\ or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.
Path.Combine Method (System.IO) | Microsoft Learn
I would like to know which process will be fired before a file is started with:
Process.Start("PathToFile");
Then I would like to have the path to the process.
Thank you.
You can look at the MainModule property of the Process returned from Process.Start:
Process p = Process.Start(#"D:\\test.txt");
string executableStarted = p.MainModule.FileName; // full path to notepad.exe
However, you should remember that the return value from Proces.Start might be null - according to MSDN, the return value is:
A new Process component that is
associated with the process resource,
or null, if no process resource is
started (for example, if an existing
process is reused).
Update
In order to know the executable prior to launching the process, you will have to look under HKEY_CLASSES_ROOT in the registry. This would be the code for going from a file name to the command the shell will execute when opening the file:
string extension = Path.GetExtension(path);
var regClasses = Microsoft.Win32.Registry.ClassesRoot;
var extensionKey = regClasses.OpenSubKey(extension);
var typeKey = extensionKey.GetValue(String.Empty);
var cmdKey = regClasses.OpenSubKey(typeKey + #"\shell\open\command");
string command = cmdKey.GetValue(null) as string;
It returns a Process object containing more information. MainModule might be the right property for you.
http://msdn.microsoft.com/en-US/library/system.diagnostics.process.mainmodule(v=VS.80).aspx
EDIT:
Do you want to know it before/without
starting the process? -Yes
You could lookup the registered file handler in the registry - for .doc, .txt, etc.
Documents that you want to use the windows file association to open
I found this link here that explains how to create a file association. This may help. Of course you'll need to read the registry. There are two formats that I know of.
Programs to which you don't know the path
The path environment variable is consulted after the current directory as default paths to look in when the path is not provided.
The Path environment variable can help you here.
public static string GetPath (string pathToFile)
{
string fileNameOnly = Path.GetFileName(pathToFile);
List<string> folders = Environment.GetEnvironmentVariable("Path").Split(';').ToList ();
folders.Insert(0, Environment.CurrentDirectory);
foreach (string folder in folders)
{
string fileName;
try
{
// Can't trust that the Path environment variable is constructed correctly.
fileName = Path.Combine(folder, fileNameOnly);
}
catch
{
continue;
}
if (File.Exists(fileName))
return fileName;
}
return null;
}
Edit: Added link to MS: path.
Edit: Added another link.
I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :
Could not find a part of the path
'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}
Could anyone please tell me how should I save a file at my desirable folder with specifying complete path?
When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.
Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.
As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.
You need to make sure the directory exists prior to creating the text file.
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
if (!info.Directory.Exists)
info.Directory.Create();
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}