Code unable to reference to local directory - c#

The situation is like this:
I am modifying someone's code to download an image file from a shared path. So the person hardcoded the piece of code to be #"\\" + local_path
Since the call is expected to go and download from the shared path \\network\bla\bla\bla, it is fine to get hardcode in this way.
Now my problem come in, I actually need to modify some other parts and test it out in playback mode before I deliver this for actual use. However, my work guideline is not to delete away the #"\\" appended. Because, without the #"\\" the path would not link to the share directory and this changed .dll could not be used for actual activity.
Yet with this, if I were to use playback, the file path will now be \\C:\temp\Images, which will be wrong. My problem now is, how to maintain the ability of the code to link to share path and at the same time create a path local so that the code can reference to.

The UNC path \\localhost\C$\ will access the drive C: on your local computer.

The easiest solution is to simply provide a flag which indicates the type of path you want to create e.g.
public string BuildPath(bool isUnc, params string[] pathParts)
{
var path = Path.Combine(pathParts);
return isUnc ? #"\\" + path : path;
}
...
var uncPath = BuildPath(isUnc: true, "network", "bla", "bla", "bla");
var localPath = BuildPath(isUnc: false, #"C:\", "temp", "images");

Related

I think I am doing this wrong, won't copy to relative path

public void Save_Token(string _Token)
{
var Token_Location = #".\token.txt";
using (StreamWriter sw = new StreamWriter(Token_Location))
{
sw.WriteLine(_Token);
}
}
I tried to get the token from the api (json) and I deserialized and saved it. I would like to write to the file to save for later. But I want this application to be ran on anyone's PC. So I don't want to use the full path.
I also tried
Path.Combine(Environment.CurrentDirectory,Token_Location);
still nothing is written, unless I use the full path.
You can't guarantee that the current user has write access to the folder from where the file is executed. There is a special folder (APP_DATA) that applications are supposed to use when storing user data on a computer:
public void Save_Token(string _Token)
{
var tokenDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourCompanyOrOrganizationName");
var tokenFile = Path.Combine(tokenDirectory, "token.txt");
Directory.CreateDirectory(tokenDirectory);
File.WriteAllText(tokenFile, _Token);
}
Your file will then be stored in a path like "C:\Users\yourusername\AppData\Roaming\YourCompanyOrOrganizationName\token.txt"
It is generally a bad idea to use a relative path in software source code because the "current working directory" of the process that the relative path is relative to can change over the runtime of the application.
Activities like showing a file open dialog or using a third-party component can unexpectedly change the current working directory so that it is dangerous to assume a certain current working directory.

Reading a setting file on server

I am writing a web service which currently needs to read some settings from a json file on server.
string allSettingsTxt = File.ReadAllText(settingsPath);
List<MySetting> list = JsonConvert.DeserializeObject<List<MySetting>(allSettingsTxt);
I tried giving following for the path
string settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\MyCurrentDir\setting.json");
But this path wont resolve on the actual deployment, I believe it has to be something like http://servername/settings/setting.json ??
Where can I store such json file
what path I should use to access it?
I'm not totally sure if I understand correctly what you are trying to achieve.
I assume you want to get the path of the settings file which is relative to your executable file.
This is what I do often in my own code:
var configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.xml");
In this case, config.xml is expected to be in the same directory as the .EXE.
So this would be
var settingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"..\MyCurrentDir\setting.json");
in your case.
Also see https://dailydotnettips.com/different-ways-of-getting-path/ for some explanations.

C# Application Relative Paths

I just started learning C# and it looks like when you are writing an output file or reading an input file, you need to provide the absolute path such as follows:
string[] words = { "Hello", "World", "to", "a", "file", "test" };
using (StreamWriter sw = new StreamWriter(#"C:\Users\jackf_000\Projects\C#\First\First\output.txt"))
{
foreach (string word in words)
{
sw.WriteLine(word);
}
sw.Close();
}
MSDN's examples make it look like you need to provide the absolute directory when instantiating a StreamWriter:
https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
I have written in both C++ and Python and you do not need to provide the absolute directory when accessing files in those languages, just the path from the executable/script. It seems like an inconvenience to have to specify an absolute path every time you want to read or write a file.
Is there any quick way to grab the current directory and convert it to a string, combining it with the outfile string name? And is it good style to use the absolute directory or is it preferred to, if it's possible, quickly combine it with the "current directory" string?
Thanks.
You don't need to specify full directory everytime, relative directory also work for C#, you can get current directory using following way-
Gets the current working directory of the application.
string directory = Directory.GetCurrentDirectory();
Gets or sets the fully qualified path of the current working directory.
string directory = Environment.CurrentDirectory;
Get program executable path
string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Resource Link 1 Resource Link 2
defiantly, you no need specify full path , what is the good way you perform this type of criteria?
should use relative path #p.s.w.g mention already by comment to use Directory.GetCurrentDirectory and Path.Combine
some more specify by flowing way
You can get the .exe location of your app with System.Reflection.Assembly.GetExecutingAssembly().Location.
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);
on the other hand
Internally, when getting Environment.CurrentDirectory it will call Directory.GetCurrentDirectory and when setting Environment.CurrentDirectory it will call Directory.SetCurrentDirectory.
Just pick a favorite and go with it.
thank you welcome C# i hope it will help you to move forward

How do i access and create txt files in the same directory as the program in c#

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.

The SaveAs method is configured to require a rooted path, and the path <blah> is not rooted

OK I've seen a few people with this issue - but I'm already using a file path, not a relative path. My code works fine on my PC, but when another developer goes to upload an image they get this error. I thought it was a security permission thing on the folder - but the system account has full access to the folder (though I get confused about how to test which account the application is running under). Also usually running locally doesn't often give you too many security issues :)
A code snippet:
Guid fileIdentifier = Guid.NewGuid();
CurrentUserInfo currentUser = CMSContext.CurrentUser;
string identifier = currentUser.UserName.Replace(" ", "") + "_" + fileIdentifier.ToString();
string fileName1 = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);
string Name = System.IO.Path.GetFileNameWithoutExtension(fileName1);
string renamedFile = fileName1.Replace(Name, identifier);
string path = ConfigurationManager.AppSettings["MemberPhotoRepository"];
String filenameToWriteTo = path + currentUser.UserName.Replace(" ", "") + fileName1;
fileUpload.PostedFile.SaveAs(filenameToWriteTo);
Where my config settings value is:
Again this works fine on my PC! (And I checked the other person has the folder on their PC).
Any suggestions would be appreciated - thanks :)
Obviously what it says is that your filenameToWriteTo is not a rooted path... ie it is a relative path, and your server configuration doesn't like that. Use Server.MapPath to obtain real paths... something like...
string realPhysicalPath = Path.Combine(Server.MapPath(" "), filenameToWriteTo);
fileUpload.PostedFile.SaveAs(realPhysicalPath);
Just in case print out your filenameToWriteTo to see if its relative or physical path. If it's relative use the approach above.
Not sure what the issue was as it sorted itself out. We didn't end up debugging it as it was on a non developer's PC and I had a workaround for him to continue his work whilst I investigated potential causes. So maybe was the way he updated/ran the site or file permissions fixed by grabbing a copy of my directory.
At least I know it needs physical file paths so hopefully won't come across this again!
Please, make sure that folder where you are saving the file exists. If folder does not exist, it will not be created for you and SaveAs method will throw exception you are having now.
Thank you.

Categories