I try to write some data with streamwriter in a .txt file and than to use those as cookies
var writer = new System.IO.StreamWriter(Application.StartupPath +
"\Cookies\cookies.txt");
But after I install application from .exe file and execute, it shows the error "Access is denied in path ..."
I am not sure if the problem is in path of file that I want to use as a file for cookies or in process of creating installation MSI/Setup of Application, even I include Cookies folder in application.
Do you have any suggestion which is the best practice to save "cookies" in win application?
Seems your source code is under some place where file writing is allowed, but when you running your exe then the location of the execution is not allowed for file write. Because you are writting your file in the exe execution path so file write permission is depend upon that execution location. If you execute exe from a location where file write alowed it won't throw exception and if a flace where file write is not allowed then it will throw exception. So my suggestion is use a allowed static place where user have file write permission, like AppData or Documents like below
var writer = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\Cookies\cookies.txt");
or
var writer = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Cookies\cookies.txt");
Hope it will help
irst are you sure that the needed folder is under the proper folder structure? Because StartupPath will return the path to your exe file ?
Related
I'm experiencing an issue with an FTP watcher service and the File.Move method.
The FTP server is a simple IIS 8.5 FTP site and the FTP client is FileZilla FTP Client
The windows service will poll a directory where the files are to be dropped.
The first task is to rename the file, using the static File.Move method.
The second, is to copy the file to another directory using the static File.Copy method.
The issue is that while the file is being transferred, the File.Copy will [correctly] throw an IO Exception if it is used, with the message "The file is being used by another process".
However the File.Move will perform it's task without throwing any exception while the file is still being transferred. Is this the correct behavior for this method? I've not been able to find any information on why this occurs. My impression was that the File.Move would throw an exception if it's used on a file that's being used by another process [The FTP Transfer] but it doesn't seem to.
Has anyone experienced this and / or have an explanation for the behavior of the File.Move method
Copying a file requires opening it for read access. The FTP server currently has the file open such that you cannot open it for reading.
Moving a file does not require opening it for read access unless the file is on a different volume than the destination.
Since moving a file to the same volume requires only delete access and not read access, the FTP server must lock the files for read and write, but not delete.
This code shows that File.Move will indeed throw an exception if the file is in use when you try to move it, so I think your premise is incorrect.
var filePath = #"d:\public\temp\temp.txt";
var moveToPath = #"d:\public\temp\temp2.txt";
// Create a stream reader so the file is 'in use'
using (var fileStream = new StreamReader(filePath))
{
// This will fail with an IO exception
File.Move(filePath, moveToPath);
}
Exception:
The process cannot access the file because it is being used by another process.
Moving a file is effectively implemented as a mere rename and only requires write permission on the target and source directory. For a real copy you need read permissions on the file itself. As there is an exclusive lock on the source file, the copy will fail, however, the move will succeed.
I created a PDF webapp where users are able to generate various type of PDF on both the computer and mobile phone. However, i run my program on a localhost and this is how i save my PDF based on my computer's file directory
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
However, when i publish my webapp onto azure, i wasn't able to download from both my computer and mobile phone. Therefore i believe that it could be due to my default file directory.
Hence i would like to ask how to do a default file directory for all computer and mobile phone?
Or could it be i left out something that is necessary when the webapp is published online
Thanks.
PS : I hardcoded a default file path in order for me to test my application on a localhost to ensure a perfect working condition. Therefore i'm finding a way to find a default common file directory for all mobile/computer users when they attempt to download the PDF instead of my usual hard-coded file path
UPDATE
I tried using the method Server.MapPath but receive some error.
var doc1 = new Document();
var filename = Server.MapPath("~/pdf") + "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
// var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
//iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
using (var output = File.Create(filename))
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
}
doc1.Open();
This is the error i received
ObjectDisposedException was unhandled by user code
Cannot access a closed file.
When you write a Web Application you shall never use hard coded paths, and the last place where you should save files is C:\Users !! It does not matter whether this is Azure or not. It is general rule for any kind of web applications!
In your case I suggest that you create a folder within your application named pdf or something like that and save files there with the following code:
var fileName = Server.MapPath("~/pdf") + filename;
using (var output = File.Create(fileName) )
{
// do what you want with that stream
// usually generate the file and send to the end user
}
However there is even more efficient way. Use the Response.OutputStream and write the resulted PDF directly to the response. Will save you a lot of space on the local server, and the logic to delete unused generated files.
I'm trying to write an xml file and attach it to an email. It works great if I give it a path to my personal documents folder(i.e. C:\users\myname\Documents\Test.xml), but if I try to change it to something like C:\\Test.xml, I get the following error message:
UnauthorizedAccessException was Unhandled Access to the path
'C:\Test.xml' is denied.
(I can't post pictures apparently)
What would be a good workaround for this?
To get the directory in which the application is launched you could use AppDomain.CurrentDomain.BaseDirectory
On Admin privileges:
Check if the user has launched the application using Run as Administrator.
In this case user should have admin privileges to write..Here is sample code..
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
//Application is Running as ADMIN
}
You could always write it to you TEMP or LOCAL APP DATA folder..
var temp = Path.GetTempPath();
//e.g: C:\Users\UserName\AppData\Local\Temp\test.xml
var testFilePath = Path.Combine(temp, "test.xml");
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
see How can I get the application's path in a .NET console application?
Program folder is not always allowed to write, use %TEMP% folder instead.
I have an application MVC3 application. I want to log various things, like when a form particular form is submitted, to avoid having to write to a database, I want to log the details in an xml file.
The question is what folder should I use, some of the examples I have seen suggest the App_Data folder. What is the norm or recommended for the least issues?
So I use this:
// Create a new XmlSerializer instance with the type of the test class
var serializerObj = new XmlSerializer(typeof(CourseApplicationVM));
// Create a new file stream to write the serialized object to a file
var filename = string.Format("{0}-{1}-{2}{3}", "CourseApp",
viewModel.Course.Code + viewModel.Applicant.Name, DateTime.Now.Ticks, ".xml");
var filepath = Path.Combine(Server.MapPath("~/App_Data/Log"), filename);
TextWriter writeFileStream = new StreamWriter(filepath);
serializerObj.Serialize(writeFileStream, viewModel);
// Cleanup
writeFileStream.Close();
It works fine locally, but not when published to the server. Upon looking at the folder structure it is unsurprising, as it doesn't even have the App_Data folder when published. Which leads to this error:
Could not find a part of the path 'C:\inetpub\wwwroot\MyApplication\App_Data\Log\CourseApp-0385JoeBloggs-634734549879496695.xml'.
Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\inetpub\wwwroot\MyApplication\App_Data\Log\CourseApp-0385JoeBloggs-634734549879496695.xml'.
Why is it that is hasn't got that folder (shouldn't it be published up)? And what is the normal location for the saving of such things?
Thanks,
David
Right Click on the folder and in context menu select "Include in to project/solution"
Make sure you rights on folder are set accordingly.
I have shared hosting account on some hosting service provider. So, I can upload pics or something else through FTP. For instance, my ASP .NET binaries are in /mysite.com/www/bin. But how can I set logging to file in my app? I should use real paths for that purpose. I even try just write to current directory, but I can see this log file through FTP. It just writes to some tmp path as I guess, like '' which couldn't be accessed through FTP.
So how can I setup file path for logging?
This is how I try to write to current binaries directory:
using (StreamWriter sw = new StreamWriter(String.Format("{0}{1}{2}", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "\", "log.txt"), true))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.WriteLine("------------");
sw.Flush();
sw.Close();
}
It write to some long windows path, which I guess it uses for some temporary storing of binaries.
Assuming your question is "I have FTP server running and serving content of "C:\myFTP\" how can I write log files (i.e. from ASP.Net application) to file available via FTP from the server?"
Answer - just write logs to that "C:\myFTP" location (or whatever location your local FTP server is configured to serve.
I solved it myself. You should use HttpContext.Current.Server.MapPath for that.