Read a file from an unknown location? - c#

I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks

You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.

If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);

If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.

You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);

Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();

Related

C# Filestream denied access

I'm trying to use C# to create a file, and read files back to fill out a rich text block. right now my problem is in creating/writing to the file.
FileStream fs = File.Create(#".\\tmp\" + fileName);
This is where I'm trying to write to. .\tmp\ exists, but when trying to write it it errors, saying
.\tmp\filename access is denied
The probably is that the user that is running the application probably doesn't have access to write to that directory. The easiest way to test that would be to run your application as administrator you should have access to write to that directory then.
You might also want to consider writing to the current directory no matter what user who is running your application should at the very least have access to that directory
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Probably you don't have access to the relative path.
To get your assembly directory:
private static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Then
FileStream fs = File.Create(Path.Combine(AssemblyDirectory, fileName));
You are using a relative path which leads to a location which you don't have access to.
A possible solution could be to:
Create a folder C:/data and make sure you have read and write rights to that folder
change the code to
string fileName = "file.txt";
FileStream fs = File.Create(#"C:/data/" + fileName);
This should create a file under C:/data with the filename "file.txt", assuming you have the correct read and write rights.
If you want a relative path to the current user's root directory, use:
string currentUserDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
This happened to me . I had had an anti-virus blocking access to any file when the writing or reading process happening from a C# program. I have just deactivated the anti-virus and the code worked like magic !

Moving up a folder from the executable

I am trying to make a file path inside of the folder above the executable. For instance, I am wanting the variable TAGPATH to be the filepath to an executable in the folder C:\User\ApplicationFolder\tag_rw\tag_rw.exe while the application is in C:\User\ApplicationFolder\AppFiles. I want the application to be portable, meaning no matter the folder names it will retrieve the filepath of the application's executable then go to the parent folder and navigate into tag_rw\tag_rw.exe.
I basically want string TAGPATH = #"path_to_appfolder\\tag_rw\\tag_rw.exe"
Here is what I have tired so far (using the first answer How to navigate a few folders up? ):
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string TAGPATH = System.IO.Path.GetFullPath(System.IO.Path.Combine(appPath, #"..\"));
I am getting a run-time error ArgumentException with the description URI formats are not supported.
Is there an easier/better way to go about this?
Thank you!
Can you try this?
static void Main(string[] args)
{
string cur = Environment.CurrentDirectory;
Console.WriteLine(cur);
string parent1 = Path.Combine(cur, #"..\");
Console.WriteLine(new DirectoryInfo(parent1).FullName);
string parent2 = Path.Combine(cur, #"..\..\");
Console.WriteLine(new DirectoryInfo(parent2).FullName);
Console.ReadLine();
}
Navigation is limited to absolute and relative types. I think you mean to navigate to parent directory regardless of whole application location.
Maybe you try relative path
string TAGPATH = "..\\tag_rw\\tagrw.exe"

System.UnauthorizedAccessException while creating a file

I was trying to write a code so that I could log the error messages. I am trying to name the file with the date and would like to create a new log file for each day. After going through a little look around, I came with the following code...
class ErrorLog
{
public void WriteErrorToFile(string error)
{
//http://msdn.microsoft.com/en-us/library/aa326721.aspx refer for more info
string fileName = DateTime.Now.ToString("dd-MM-yy", DateTimeFormatInfo.InvariantInfo);
//# symbol helps to ignore that escape sequence thing
string filePath = #"c:\users\MyName\mydocuments\visual studio 2012\projects\training\" +
#"discussionboard\ErrorLog\" + fileName + ".txt";
if (File.Exists(filePath))
{
// File.SetAttributes(filePath, FileAttributes.Normal);
File.WriteAllText(filePath, error);
}
else
{
Directory.CreateDirectory(filePath);
// File.SetAttributes(filePath, FileAttributes.Normal)
//Throws unauthorized access exception
RemoveReadOnlyAccess(filePath);
File.WriteAllText(filePath, error);
}
}
public static void RemoveReadOnlyAccess(string pathToFile)
{
FileInfo myFileInfo = new FileInfo(pathToFile);
myFileInfo.IsReadOnly = false;
myFileInfo.Refresh();
}
/*Exception thrown:
* UnAuthorizedAccessException was unhandled.
* Access to the path 'c:\users\anish\mydocuments\visual studio 2012\
* projects\training\discussionboard\ErrorLog\04\12\2013.txt' is denied.
*/
}
I found a forum that has discussed about a similar problem but using
File.SetAttrributes(filePath, FileAttributes.Normal) did not help neither did the RemoveReadOnlyAccess (included in the code above). When I check the properties of the folder, it has read only marked but even when I tick that off it comes back again. I checked the permissions on the folder and except for the special permission, which I was not able to change, everything is allowed.
Any suggestion on how I should proceed would be appreciated.
Why is access to the path denied? the link discusses about a similar problem, but I wasn't able to get my thing working with suggestions listed there.
Thanks for taking time to look at this.
Your path is strange : "My documents" directory must be "C:\Users\MyName\Documents\"
You can use Environment in order to correct it easily :
String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Note that it will acces to "My documents" folder of the user that running your exe.
Second error, CreateDirectory must have a path in argument, not a file. using like you do will create a sub-directory with the file name. So you can't create a file with this name !
Try this :
String fileName = DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);
String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ #"\visual studio 2012\projects\training\discussionboard\ErrorLog\";
String fileFullName = filePath + fileName + ".txt";
if (File.Exists(fileFullName ))
{
File.WriteAllText(fileFullName , error);
}
else
{
Directory.CreateDirectory(filePath);
[...]
}
}
Some possible reasons:
your app is not running under account which is allowed to access that path/file
the file is being locked for writing (or maybe reading too) by some other process
The first situation could be solved by checking under which account the process is running and verifying that the account has the appropriate rights.
The other situation can be solved by checking if any other process is locking the file (e.g. use tools like 'WhosLocking' or 'ProcessExplorer'
I had to run my app as an administrator in order to write to protected folders in c:. For example if debugging your app in visual studio make sure to right click on "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" and choose "Run As Administrator". Then open your solution from there. My app was trying to write to the root of c:\
Check your antivirus, it might be blocking the file creation.

Managing absolute path and full path

I've created a small program wich can read a .txt file.
This file contains a link to another file in this format new_file.txt
The goal is to return the path of the new file, so basically I'm doing this :
String newFileName = getFileName();
int index = oldFilePath.lastIndexOf('\\');
String path = oldFilePath.substring(0, index + 1);
String newFilePath = path + newFileName;
return newFilePath;
For example :
The first file I opened is : C:\a\b\c\oldFile.txt
In this file I found newFile.txt
So the new path will be : C:\a\b\c\newFile.txt
Nice, but what If I find something like this :
..\ or .\.\ or ...
Is there any way to automate this mess ?
Thanks
In C#/.Net you have the rather cool Path class.
You can use Path.GetFullPath( string pathname ) to resolve paths e.g. with \..\ etc in them.
Use Path.GetDirectory(), Path.GetFileName(), Path.GetFileNameWithoutExtension() & Path.GetExtension() to pull names apart and Path.Combine() to put them back together again.
You've tagged this as java as well as c#
In java look at FileNameUtils http://commons.apache.org/io/apidocs/org/apache/commons/io/FilenameUtils.html
The normalize method should help

I have a problem with the function Directory.delete?

Take a look at my code:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
try
{
if (Directory.Exists(Path.Combine(desktopPath, "Hackers.avi")))
Directory.Delete(Path.Combine(desktopPath, "Hackers.avi"), true);
after runing the file is still exist on my desktop , why??
It is unlikely that Hackers.avi is a directory - .avi is normally used an extension for a video file (see Audio Video Interleave on Wikipedia for more information).
Try using File.Delete instead of Directory.Delete:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
try
{
string pathToFile = Path.Combine(desktopPath, "Hackers.avi");
File.Delete(pathToFile);
// etc...
I also omitted the call to File.Exists because you don't have to check for a file's existence before deleting it. File.Delete does not throw if the file doesn't exist.
You want to delete file, sou you must use 'File.Delete'

Categories

Resources