C# Copy file to folder with permissions - c#

I'm writing a program that, among other things, needs to copy a particular file to a network folder. Since I'm on a company network, the credentials needed to access that folder are the same as my Windows credentials.
The program works if I open the folder in Explorer, provide my username and password, and then run the uploader. It doesn't work without first providing that username and password.
How do I tell System.IO to supply my DefaultNetworkCredentials to the Copy method? Or is there another method I can use to get this done?
string pathToFile = "myfile.csv";
string pathToRemoteFile = "\\server.domain.tld\Documents\Subfolder\myfile.csv"
System.IO.File.Copy(pathToFile, pathToRemoteFile); // Fails with IOException "can't find network path"
Thanks!
~ Wogan

The error suggests that it is an incorrect path rather than a permissions problem.
Try this:
string pathToRemoteFile = #"\\server.domain.tld\Documents\Subfolder\myfile.csv"
[The # is the string literal quoting symbol; without it the backslash is a special character]

Related

C# File.exists returns false

I have a program that opens a database, the path to that database is this:
private static string strDefaultDB2 = #"C:\Users\" + Environment.UserName + #"\OneDrive\TIME FILE\MyName\TimeFile.accdb";
All computers I have tried this one were able to access it fine except one, it also has access to OneDrive but when I run the code the file doesn't exist... If I enter the path generated by the code which is something like this:
C:\Users\UserName\OneDrive\TIME FILE\MyName\TimeFile.accdb
In explorer, it opens up the database right away. I'm not sure why it can't find the database on this one machine... I also tried running it as admin but that didn't change anything
This is the code that executes:
if (!System.IO.File.Exists(doesFileExist))
{
Polaris.Polaris.log("The Path " + doesFileExist + " Does Not Exist!");
runWindowDB();
}
If I try to do a rename on the file it throws an exception: "Could not find file [path]"
And If I try to open the database: "[path] is not a valid path"
I don't get it because this path has whitespace on every pc and the only thing that changes is the username. Explorer opens the file so the path is correct.
Any ideas?
Thanks
Do you get an exception? Can you read/write this file?
You have a whitespace in the string I don't think that is good anyway.
From the official documentation link:
If path describes a directory, this method returns false. Trailing
spaces are removed from the path parameter before determining if the
file exists.
The Exists method returns false if any error occurs while trying to
determine if the specified file exists. This can occur in situations
that raise exceptions such as passing a file name with invalid
characters or too many characters, a failing or missing disk, or if
the caller does not have permission to read the file.
Hard code another users username that you know works, try it from this machine, msdn mentions it will return false if there are invalid characters in the string or if the path is determined to be a folder, there might be some odd encoding going on or virus scanner intercepting the io. If that fails try getting the user to log onto another box that works and if the file is then recognized it must the environment on that users original box.

My C# code can't see my directory in my C drive...even though the directory exists

My directory is at C:\Testing\Event Log 123
The 123 portion is a timestamp. My code runs and generates a timestamped directory in C:\Testing upon completion. I have this piece of code that checks if that directory exists:
string dirToCopy = #"C:\Testing\Event Log " + timestamp;
if (System.IO.Directory.Exists(dirToCopy))
{
APILog.AddMessage("Event System log directory found.");
}
else
{
APILog.AddMessage("Event System log directory not found.");
}
The directory does exist at that location, but the else statement's log message is what gets displayed. I don't think there's an issue with permissions, as I'd be getting a security exception if that was the case...so why can't my code see the directory that I can see with my own eyeballs right now? I tried outputting dirToCopy to make sure that it matches the directory's actual name. They match, so I'm surprised that my code doesn't see it.
Edit for more info: My code runs on a client PC. It generates the directory and pastes it into the main PC's C:\Testing directory. The main PC's C:\Testing directory is a sort of shared directory that the client can also access. Does this matter, though? C:\Testing is on the main PC, and I'm running the code on the main PC.
So the directory You're looking for is "C:\Testing\Event Log2016.01.26"
or maybe "C:\Testing\Event Log\2016.01.26"
the point being - the slash at the end ? isn't it missing ?
you could also consider using Path.Combine() for building the path string
This is what MSDN says
If you do not have at a minimum read-only permission to the directory, the Exists method will return false.
https://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx
So it does not throws security exception....so do check once if you have read permission on that directory
Update
If it is shared directory then your path should look like this
string dirToCopy = #"\\MainPC\Testing\Event Log 123" (Assuming testing folder is shared)
If it is UNC path then your path should like this
string dirToCopy = #"\\MainPC\C$\Testing\Event Log 123"

How can I include saving in a text file in executable file?

I have an application in Visual Studio C# which includes saving into a text file, how can I have a .exe sent to another computer and not have an exception in saving?
I need to send a .exe file by email (Yes it's possible) and this application includes saving the state of the game. How can I send this .exe file and let the user be able to save in his computer please?
The problem is that when I send my application's executable file on another computer, I'm getting an exception in saving. Because on the other computer I don't have the text file which I'm saving the game.
I am saving here :
StreamWriter myFile = File.CreateText(Directory.GetCurrentDirectory()+"//ConnectFour.txt");
in the obj/Debug/ of the project..
Thanks for your help :)
Sending an executable should work just fine.
Make sure the other computer has the appropriate Microsoft .NET Framework installed.
Latest framework installer: MSDN
Also, make sure the path inwhich you're saving the file to exists on the remote computer. For example, if you're trying to save to the D:\ drive and it doesn't exist. You will get an exception.
Most likely current location is not writable by current user.
Using "current directory" is dangerous as you have no control over where application is launched from. It is very useful for command line utilities, but not so much for regular windowed applications. Use location that you know you can save files to - i.e. "My Documents".
var filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\",
ConnectFour.txt");
using(var myFile = File.CreateText(filePAth))
{
// save data here.
}
The problem when sending executables by email are the anti-virus-scanners. Some of them refuse e-mails containing executables. Others accept the mails but delete the attachment.
The solution consists in hiding the executable. This can be done by zipping the executable and sending the zip-file.
Often this is enough to solve the problem but some anti-virus-scanners are very smart and even recognize executables within the zip-attachment. The solution here is to encrypt the zip-file with a password. I often just use the password "pwd" and mention it in the e-mail text. The anti-viruses are not (yet) smart enough to understand this text.
UPDATE
Now I understand your problem. It has nothing to do with sending the executable.
An application can determine from which directory it has been started like this
string dir = System.IO.Path.GetDirectoryName(
System.Windows.Forms.Application.ExecutablePath
);
An alternative is (if you don't have a reference to WinForms):
string dir = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location
);
You probably do not have sufficient privileges to save the file on the remote machine. If you give us more information on the exact exception that is being thrown (type of exception, message, stack trace, etc) you will get a more accurate answer.

"Could not find a part of the path" C:\Users\username\abc\abc.exe.config

configFilePath = #"C:\Users\" + userName + #"\abc\abc.exe.config";
if(File.Exists(configFilePath))
{
StreamReader fileReader = new StreamReader(configFilePath);
}
The above line throws "could not find part of the path" exception. This error occurs in a particular machine. In all other machines it works fine. And even in that machine , the same code worked before. No changes made in the machine. I have read all the forums where this issue had been discussed. But couldn't able to figure out why this happens in that machine alone and that too now. Having permissions to access the folder and file.
First, use Path.Combine() rather than string concatenation for paths. However, the user name may contain a character that is invalid in a path, such as a single quote, so it may have been escaped. Assuming "C:\Users" is the users' directory and not your own folder structure, a better solution is to lookup the user profile folder for that user using the Environment.GetFolderPath() method with the UserProfile value from the SpecialFolders enumeration.
Something else to think about is permissions on the file/folder. I've run into issues where all of a sudden the folder security gets out of whack because of a windows update.

Getting a user specific path without knowing the username

I have a HTML file in C:\Users\myusername\AppData\Roaming\myapp\file.html. I am accessing the file through a web Browser in my C# application to preview it from within the app.
However, when the app is put onto another computer, the address in webBrowser1 is still specific to my username, and therefore other people cannot access the preview.
Is there a way to get to the file as a URL in my web Browser without having the hard coded username in the URL?
What I have tried:
C:\Users\%USERNAME%\AppData\Roaming\myapp\file.html
C:\Users\AppData\Roaming\myapp\file.html
Thanks!
Here is the code I used after I was helped:
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string address = Path.Combine(folderPath + #"\myapp\file.html");
webBrowser1.Navigate(address);
If you want to get the name of the current logged in user you have to read Environment.UserName property.
Moreover if you need to access the AppData directory for the roaming user you can get the folder path without hard-coding anything (do not forget that users directory isn't always c:\users on every Windows version and path for AppData may vary too):
string folderPath = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
In you case simply append the file name:
string url = Path.Combine(folderPath, "file.htm");
Notes
If, for any reason, you need to use environment variables then you have first to expand them:
string path = Environment.ExpandEnvironmentVariables(#"C:\Users\%USERNAME%\");
Have a look at this function. It returns the path of Current User's Application Data Folder.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Categories

Resources