I have a form on an ASP.Net MVC website where users are supposed to upload files, Here's my code:
...
if (file.ContentLength > 4194304 || file.FileName.Length <= 0)
{
ViewBag.Error = "Invalid file format or size";
}
fileName = Path.GetFileName(file.FileName);
...
var path = Path.Combine(Server.MapPath("~/App_Data/Folder"), Model.UploadedFile);
file.SaveAs(path);
the code works fine most of the time but occasionally the following exception is thrown:
System.ArgumentException: Illegal characters in path. at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename)
However I noticed that every time this exception is thrown the user was using an Android device (Sample UserAgent: Mozilla/5.0 (Linux; Android 4.4.2; ar-ae; SAMSUNG GT-I9301I Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36).
I tried uploading files using my Android device and it works fine, so any ideas?
So the error is coming from Path.GetFileName() method. This is due to illegal characters in a file name. You can find illegal characters with method Path.GetInvalidPathChars(). So if the file name has one of those illegal characters, you can handle it.
References:
Path.GetFileName Method (String): https://msdn.microsoft.com/en-us/library/system.io.path.getfilename%28v=vs.110%29.aspx
Path.GetInvalidPathChars Method (): https://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars%28v=vs.110%29.aspx
Related
Background
I currently have a usb device which has all my projects which I am working on and it stays in my office's docking station. Last night I was bored and wanted to continue work on a project, However no files? This made me think about writing a console app that would copy all the files from my usb drive to a folder on my desktop and would run as a scheduled task at a certain hour.
Problem
I am trying to use a System.IO.Compression.FileSystem in order to compress the file in order in order to then move it to a new directory on my PC. The documentation gives an example here ZipFile class. IT seems very up front. However, when I am trying to copy it to a new destination I get the following error.
Error
Message
Access to the path 'C:\Users\er4505\Desktop' is denied.
StackTrace
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable`1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName)
at ConsoleApp1.Program.Main(String[] args) in C:\FTG\Projects\CaseWare\ConsoleApp1\Program.cs:line 25
Code
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] folders = System.IO.Directory.GetDirectories(#"D:\", "*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string folder in folders)
{
ZipFile.CreateFromDirectory(folder, path); << errors out here!
}
The 2nd parameter string destinationArchiveFileName should be a filename.
for Example "C:\Users\er4505\Desktop\example.zip"
*
Exception =System.Net.WebException: Access to the path
'c:\windows\system32\inetsrv\Dialer' is denied. --->
System.UnauthorizedAccessException: Access to the path
'c:\windows\system32\inetsrv\Dialer' is denied. at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess
access, Int32 rights, Boolean useRights, FileShare share, Int32
bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy, Boolean useLongPath) at
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
access, FileShare share, Int32 bufferSize, FileOptions options, String
msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String
path, FileMode mode, FileAccess access, FileShare share) at
System.Net.FileWebStream..ctor(FileWebRequest request, String path,
FileMode mode, FileAccess access, FileShare sharing) at
System.Net.FileWebRequest.GetRequestStreamCallback(Object state)
--- End of inner exception stack trace --- at System.Net.WebClient.UploadDataInternal(Uri address, String method,
Byte[] data, WebRequest& request) at
System.Net.WebClient.UploadString(Uri address, String method, String
data)
*
Code where the exception is occurring
using (var writer = new StringWriter())
{
JsonSerializer.Create().Serialize(writer, payLoad);
var result =client.UploadString(commDialerApiUrl,writer.ToString());
return ((T)JsonConvert.DeserializeObject(result, typeof(T)));
}
I know the code above is not ideal, however I just need to understand why even an attempt to access is made. Can anyone provide some insight please?
All right, the issue was very simple. The code was trying to make a Restful post to a blank Uri. Since the Uri was blank webclient was trying to resolve the call to a file (having the same name as the service) in inetpub.
Since no such file path was invalid, thus the i/o error.
We are getting this error message upon trying to generate a report not accessing a file. We are using IIS 7.
XXX is located on a different server than the web server.
2014-10-24 11:04:13,287 [5] ERROR FOUNDATION [(null)] - Access to the path '\\XXX \file2022.pdf' is denied.
System.UnauthorizedAccessException: Access to the path '\\XXX\file.pdf' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.WriteStreamToFile(Stream stream, String filename)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportStreamToFile(Stream stream, DiskFileDestinationOptions options)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.Export(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToDisk(ExportFormatType formatType, String fileName)
at GlobalFunctions.GenerateCrystalReport(String reportFileName, String outputFileName, List`1 params) in C:\NetProjects\branches\R7\GUIs\Foundation\App_Code\GlobalFunctions.vb:line 347
If you must access files like this make sure your Application Pool is running as a domain user with read permission to that location.
I have a Windows Service that needs to read a text file every 90 seconds or so and then do some actions. The problem is that I get 'Access Denied' errors when reading the file from a service, but I can read the file just fine from an app (using the exact same code). This is my first service so maybe I am missing something obvious? Here is the relevant code for the service (Doesn`t work)
protected override void OnStart(string[] args)
{
this.eventLog1.WriteEntry("my app in OnStart.");
ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceWorkerThread));
}
private void ServiceWorkerThread(object state)
{
while (!this.stopping)
{
update_DB();
Thread.Sleep(90000);
}
this.stoppedEvent.Set();
}
protected void update_DB()
{
try
{
var lines = File.ReadAllLines("C:\\Users\\jkoegler\\Desktop\\text.xml");
//do a bunch of other stuff
}
catch (Exception e)
{
this.eventLog1.WriteEntry(e.ToString());
}
}
And here is what gets logged:
System.UnauthorizedAccessException: Access to the path
'C:\Users\jkoegler\Desktop\text.xml' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32
rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options,
SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare
share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare
share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean
detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path, Encoding encoding)
at System.IO.File.InternalReadAllLines(String path, Encoding encoding)
Now what gets me is that I can have this EXACT same code block (update_DB()) in a button click event in a regular windows forms app and it works fine. I can run the app at basically the same time as the service and it works just fine. What gives? I gave all users full access to the file and the folder. Thanks in advance
Windows services run as a specified user. You can view or change which user it is running under using the Services control panel.
Run: services.msc
or
Access via the Control Panel->Administrative Tools->Services
By default, it is probably running under the Local Service account, and that account probably doesn't have permissions to the file you are trying to read, but your account does.
I am trying to upload an image.it works fine when i do it from my localhost but when i published it it throw an error from server:
When I use this code :
public string ImagePath(HttpPostedFileBase imgfile)
{
var path = "";
// code for saving the image file to a physical location.
var fileName = Path.GetFileName(imgfile.FileName);
path = Path.Combine(HttpContext.Server.MapPath("~/Images/Sections/Developer/ClientLogo"), fileName);
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(imgfile.FileName);
int iteration = 1;
while (System.IO.File.Exists((path)))
{
fileName = string.Concat(fileNameWithoutExtension, "-", iteration, System.IO.Path.GetExtension(imgfile.FileName));
path = Path.Combine(HttpContext.Server.MapPath("~/Images/Sections/Developer/ClientLogo"), fileName);
iteration++;
}
imgfile.SaveAs(path);
// prepare a relative path to be stored in the database and used to display later on.
path = Url.Content(Path.Combine("~/Images/Sections/Developer/ClientLogo", fileName));
return path;
}
Error is
System.UnauthorizedAccessException: Access to the path 'D:\InetPub\vhosts\xx.com\httpdocs\Images\Sections\Developer\ClientLogo\circle-small-empty.18x18.png' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at System.Web.HttpPostedFileWrapper.SaveAs(String filename) at xx.CorporateSite.Controllers.DeveloperController.ImagePath(HttpPostedFileBase imgfile)
And when I use Server.MapPath instead of HttpContext.Server.MapPath it throw different error:
Error is:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\InetPub\vhosts\xx.com\httpdocs\Images\Sections\Developer\ClientLogo\demo.png'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at System.Web.HttpPostedFileWrapper.SaveAs(String filename) at xx.CorporateSite.Controllers.DeveloperController.ImagePath(HttpPostedFileBase imgfile)
I tried to change the permission from my localhost but nothing is working...Please suggest me something
Your web application does not have permission to write to the location where you're trying to save the image. This is often handled by adding an entry to your web.config which points to a folder where all uploads are saved
<appSettings>
...
<add key="uploadPath" value="C:\Uploads"/>
...
</appSettings>
and then in your code you would read that configuration entry to identify the path where the image will be saved:
....
string path = ConfigurationManager.AppSettings["uploadPath"];
string filePath = Path.Combine(path, fileName);
....
And then in order to save the files to this directory, you would need to set permissions on the directory so that the user that the web application is running as has Write permissions on that directory. This will allow you to write files from the web application to that folder.
This way, you, as the developer, are not dictating where the files go. The system administrator can decide both where the files go, and what permissions are necessary to support your web application.
Check to see if the folder's Read-Only attribute is active. If it is uncheck it in the properties of the folder if this is a windows machine.
If it keeps reverting you may need to take ownership of the folder by going to security->advanced->effective permissions->click select...->put in your username and check full control->then click ok out.