I have simple code
using (FileStream fs = File.Create(#"newfile.txt"))
{
}
And if I give the path "E:\newfile.txt" I get the error System.IO.IOException: 'The media is write protected.'
If I give the path "C:\newfile.txt" I get no error but no file creation, even if I give the path "C:\Users\Me\Documents\newfile.txt" I get no error and no file creation.
Are these errors related, I have written to USB devices no problem before, and my C drive should not be restricted and surely the Users folder isnt restricted at all.
What am I missing?
Perhaps this might work:
string path = #"C:\Users\Me\Documents\newfile.txt"
File.AppendAllText(path,new[] {"Your text goes here"});
This will create the file if it does not exist or write to the existing one.
See Also:
Create a .txt file if doesn't exist, and if it does append a new line
Related
I'm trying to create an XML in an UNC path, using C#, but I'm getting the error "Access denied".
What I'm trying to do is:
doc.Save(#"\\someshare\somefolder\anotherfolder");
(the rest of the code is correct, I already tried on a local folder)
I guess I'll need to use some class to authenthicate on the share. But I don't know which. Could you tell me which is?
I've taken on an asp/c# web app to fix originally done by the previous developer at my workplace. The code shows a Gridview populated by results from a query showing a list of files, one column is made up of 'command fields' that when clicked download a file. Everything seems to go smoothly until it reaches the file download as it can't seem to find the file on the server. My C# really isn't strong so bear with me and if you need further info that I've missed out please do say so.
Here is the specific part of code that causes problems:
//strSuppDocName - is already declared elsewhere
string path = System.IO.Path.Combine(Server.MapPath("~/Documents/"), strSuppDocName);
if (!Directory.Exists(path)){
System.Windows.Forms.MessageBox.Show(path + " - file path doesn't exist");
}
else {
System.Net.WebClient client = new System.Net.WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ClearContent();
Response.ClearHeaders();
FileInfo file = new FileInfo(path);
Response.Clear();
Response.AddHeader("Content-Disposition", "Attachment;FileName:" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = ReturnExtension(strExtSuppDoc.ToLower());
Response.WriteFile(file.FullName);
Response.End();
}
}
What happens when I run the code is that the grid view populates okay, I click the file to download and it enters the first branch of the if statement showing the path. Before I added in the if statement it was showing the following error: "could not find a part of the path". I've tried fiddling with the path such as setting it absolutely:
string path = System.IO.Path.Combine(#"E:\web\Attestation\Documents\", strSuppDocName);
And without using the Combine method above and using standard string concatenation with '+'. Any help or guidance is most appreciated, thanks!
You're mixing a handful of technologies here. First of all, this doesn't belong in a web application:
System.Windows.Forms.MessageBox.Show(path + " - file path doesn't exist");
Web applications aren't Windows Forms applications. This won't display anything to someone using the web application, because there's no concept of a "message box" over HTTP.
More to the point, however, you're using path in two very different ways. Here:
Byte[] buffer = client.DownloadData(path);
and here:
FileInfo file = new FileInfo(path);
Is path a URL on the network or a file on the file system? It can't be both. The first line is treating it as a URL, trying to download it from a web server. The second line is treating it as a local file, trying to read it from the file system.
What is path and how are you looking to access it? If it's a URL, download it with the WebClient and stream it to the user. If it's a file, read it from the file system and stream it to the user. You can't do both at the same time.
If you are interacting with a path on a network (aka UNC path), you have to use Server.MapPath to turn a UNC path or virtual path into a physical path that .NET can understand. So anytime you're opening files, creating, updating and deleting files, opening directories and deleting directories on a network path, use Server.MapPath.
Example:
System.IO.Directory.CreateDirectory(Server.MapPath("\\server\path"));
The answer in short is that the file name was incorrect.
Strangely or mistakenly the author of the code, when uploading a given file, added an extra extension so a file would be something like 'image.png' to start off with then when uploaded would become image.png.png. Why didn't I notice this before you may ask? Simply because the whole path wasn't shown in Windows XP (don't ask why I was using XP) when viewing it through the explorer window and I dismissed this issue long before - a big mistake! After trying to find the file by typing the address of the file into the windows explorer address bar and receiving an error that the file doesn't exist, yet I could plainly see it did, a colleague looked at for the file remotely using Windows 7 and we saw that the file was shown as 'image.png.png'. Thereafter the path to the file worked correctly.
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.
I'm trying to read a xml file but everytime the code arrives at the load()-function it throws the exeption "the device is not ready". This is the code:
const string filepath = #"E:\xml\somefile.xml";
XmlDocument fileDoc = new XmlDocument();
fileDoc.Load(filepath);
The drive "E:\" is a physical HDD where the webapplication is saved in a folder called "app". So the folder xml is completely independent of the web apllication and iis. I also tried to locate the xml in the application folder but the same error occured.
Has someone an idea what I am missing?
Check if the file "E:\xml\somefile.xml" is not locked in you process when you try to read the xml. Use the right usinging of call Dispose() on the objects which write the file.
I'm having an issue here, I developed an application in C# which creates a text file. This text file is saved in the X:\Public\3rd\ASN\, the problem is that in development the files are created and saved with no issues but once I move the application into our Web Server the appplication fails and it throws out this error "Could not find a part of the path X:\Public\3rd\ASN\1175_0001.txt".
This is the code I'm using to saved the file in the directory:
w = File.CreateText("X:\Public\Public\3rd\ASN\1175ASN_0001.txt");
Keep in mind that this directory is another server.
Any help will be really appreciate it.
your X drive is a mapped network drive. You need to use the network url eg \\server\directory\Public\3rd\ASN\1175_0001.txt