I save file to server with below code but when i want to create folder says : "URI formats are not supported"
//Save File
string folderPath = MapPath(#"Attachment\");
FileUpload1.SaveAs(folderPath + name);
//Directory
Directory.CreateDirectory(folderPath+#"\111");
check exist before
string folderPath =Server.MapPath("Attachment");
if(!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
side note:
when you concat paths better to use Path.Combine
FileUpload1.SaveAs(Path.Combine(folderPath , name));
OR try with
Directory.CreateDirectory(new Uri(folderPath+#"\111").LocalPath);
since you get "URI formats are not supported" error message
Related
It is fairly common to allow users to download a file via having some path modifier in the URL
//MVC Action to download the correct file From our Content directory
public ActionResult GetFile(string name) {
string path = this.Server.MapPath("~/Content/" + name);
byte[] file = System.IO.File.ReadAllBytes(path);
return this.File(file, "html/text");
}
quoted from http://hugoware.net/blog/dude-for-real-encrypt-your-web-config
An application I'm working with has liberal path downloads ( directory based ) sprinkled throughout the application, hence it is super vulnerable to requests like "http://localhost:1100/Home/GetFile?name=../web.config" or ( ..%2fweb.config )
Is there an easy way to restrict access to the config file - do I need to provide a custom Server.MapPath with whitelisted directories - or is there a better way.
How do you secure your file downloads - are path based downloads inherently insecure?
A simple option, assuming that all files in the ~/Content directory are safe to download would be to verify that the path is actually under (or in) the ~/Content directory and not up from it, as ~/Content/../web.config would be. I might do something like this:
// MVC Action to download the correct file From our Content directory
public ActionResult GetFile(string name) {
// Safe path
var safePath = this.Server.MapPath("~/Content");
// Requested path
string path = this.Server.MapPath("~/Content/" + name);
// Make sure requested path is safe
if (!path.StartsWith(safePath))
// NOT SAFE! Do something here, like show an error message
// Read file and return it
byte[] file = System.IO.File.ReadAllBytes(path);
return this.File(file, "html/text");
}
I have looked everywhere and I can't find out how to do this; I'm so frustrated...
How can I allow the user to send (via email) the SQLite db file?
That's it in a nutshell. I can convert it to string and attach, but I want to send the actual db file. And I'm using a new phone that doesn't have an external SD card.
The app is just a form that the user fills out, then it's saved to a SQLite database. That works wonderfully. As does printing the db to string (text) and then sending it. But, I want the user to email the actual db file (so I can use C# to read, process it, and "recreate" a real form).
Or should I be using something other than SQLite?
Edit: This is as far as I've made it. It seems to work, but it does not actually attach the file or rather the file is "blank/empty". Debug log says no such file or directory. screenshot of debug log here:http://imgur.com/oyzdtuJ
//trying again to send a SQL db file
//this seems to work and shows that it's attaching a file, but the file is empty so it won't attach
//gmail will say "cant attach empty file"
private void sendFile(String email){
File myFile = this.getFileStreamPath("testresults.db");
if(myFile != null) {
Log.d("LOG PRINT SHARE DB", "File Found, Here is file location: " + myFile.toString());
}else {
Log.w("Tag", "file not found!");
}
Uri contentUri = FileProvider.getUriForFile(this, "com.columbiawestengineering.columbiawest.MainActivity", myFile);
Log.d("LOG PRINT SHARE DB", "contentUri got: here is contentUri: " + contentUri.toString());
//grant permision for app with package "com.columbiawestengineering.columbiawest", eg. before starting other app via intent
this.grantUriPermission("com.columbiawestengineering.columbiawest", contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.d("LOG PRINT SHARE DB", "permission granted, here is contentUri: " + contentUri.toString());
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/octet-stream");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "blaaa subject");
String to[] = { email };
shareIntent.putExtra(Intent.EXTRA_EMAIL, to);
shareIntent.putExtra(Intent.EXTRA_TEXT, "blah blah message");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivityForResult(Intent.createChooser(shareIntent, "Send mail..."), 1252);
//revoke permisions
this.revokeUriPermission(contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
See this answer
Android Utility to send sqlite db to server
You could do this any number of ways. I'd say posting it to a web service is easiest. If you can only use email then I'd compress and encode it and attach it to an email but that sounds painful.
Solved. FileProvider cannot access the database directory. The db file must be copied to the files directory before it is attached. See solution here:Android: FileProvider "Failed to find configured root"
I wanna to display all the files in a directory in ASP.NET. when i click on the list of files available in that it should get download to local or it should open to view?
How to achieve this ? i got all the files in directory but i don't know to make those files to download?
Thanks in advance.
In order to make the file downlodble you have to add for each file an href
eg
foreach(string fileName in Dir)
{
Response.Write("<a href='"+fileName+"'>file name...</a>");
}
ore you have to force download in such way
public static void ForceDownload(this HttpResponse Response, string virtualPath, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
}
One way to do this is to enable directory browsing in IIS.
For whatever reason, directory browsing also displays the web.config file for the directory. The following link discuses how to not show it: http://forums.iis.net/t/1149484.aspx/1
I have a GridView which has following template field that holds the filename, when the user clicks the filename, I call window.open() to open the file. My question is I can only pass relative path to window.open(). I got an error if I use full path. Is there any way I can use full path to open a file? Thanks.
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkFile" runat="server"
Text='<%# Eval("FileName")%>' OnClick="lnkFile_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Added: The actual location of the file is defined in web.config.
I have wrote following lnkFile_Click(). The old part will open a new window for the file, but I cannot pass fullpath of the file. The new part will let you have a choice to open or save the file. My question is, will this cause security issue?
protected void lnkFile_Click(object sender, System.EventArgs e)
{
string fileName = ConfigurationSettings.AppSettings["SPRAttachmentLocation"] + "\\SPR" + sprID + "\\" + ((LinkButton)sender).Text;
if (!File.Exists(fileName))
{
Exception ex = new Exception("Could not find the file, please contact your administrator.");
Response.Write("<p align=\"center\"><br /><br /><br /><br />There has been an Error: <strong>" + ex.Message + "</strong></p>\n");
return;
}
New:
byte[] bts = System.IO.File.ReadAllBytes(fileName);
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "");
Response.AddHeader("Content-Length", bts.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bts);
Response.Flush();
Response.End();
Old:
string newWindowUrl = "/SPR_Upload/SPR" + sprID + "/" + ((LinkButton)sender).Text;
string javaScript =
"<script type='text/javascript'>\n" +
"<!--\n" +
"window.open('" + newWindowUrl + "');\n" +
"// -->\n" +
"</script>\n";
Page.ClientScript.RegisterStartupScript(GetType(), "", javaScript);
}
Your question gives the impression that you think that you can open a file from the user's local computer. If that's the case, this is not possible.
Window.open expects a URL because the file is located on the server side, not the client side.
With that said, if you are trying to open a file located on the server side and you know the full path to the file; what you need to do is generate the virtual path within your application where the file can be found. You do this by creating a Virtual Directory in your APP from the IIS Admin Manager (Control Panel-->Admin Tools -->IIS Mgmt) and mapping this directory to the actual physical directory.
EDIT:
Say for example your whole website is physically located on the server on c:\inetpub\wwwroot\your_app. Let's assume your app can be accessed via http://example.com and the files you want to serve are physically located on d:\files. Assume further that you created a virtual directory for your app (as I explained above) and that you called this virtual folder public_files. If one knows the file name it should be possible to access the file by simply going to http://example.com/public_files/filename.ext. Since you in your app already know the file name, all you need to pass as parameter to window.open is this url (http://example.com/public_files/filename.txt)
You could try using the AppDomainAppVirtualPath to get the virtual path to the file.
string vPath = HttpRuntime.AppDomainAppVirtualPath + "/my/relative/path"
if the file is not located within the virtual directory there are a number of security issues you need to consider and address. in general it's not a good idea to access a file outside of the virtual directory.
if you must, then you will need to raise security permissions and grant access to the file on the network.
I am trying to download a file from the server but i am getting this error:
The process cannot access xxxx the file because it is being used by another process
This is my CODE:
string fileName="DownLoadFiles";
string filePath = hid_filepath.Value;
FileInfo file = new FileInfo(filePath);
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadFile(new Uri(fileName, filePath);
Foe ur Information:the file is not opened or not used...
Can anyone pls help me by providing whats the reason for this error and how to solve this error
wc.DownloadFile(new Uri(fileName, filePath);
There is an error in your code, there should be a target filename specified:
wc.DownloadFile(new Uri(fileName, filePath),"c:\file.tmp");