My objective is User can choose an image from any place from their desktop and upload/tweet the same to twitter. I'm struggling to set the relative path to the imagePath variable.
The path (D Drive) were my image stored. While running the application it looks in different path. This throws an error System.IO.FileNotFoundException. I tried Server.MapPath too. Assist me to resolve it.
Solved the issue as following
string filePath; string imagePath = "";
if (imgFile == null)
{
imgFile = Request.Files["imgFile"];
}
if (imgFile.FileName != "")
{
filePath = Server.MapPath("~/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filePath = filePath + Path.GetFileName(imgFile.FileName);
imgFile.SaveAs(filePath);
imagePath = Path.Combine(Server.MapPath(#"~/Images/"), filePath);
}
File must be saved in the server location, try to replace the below instruction:
string imagePath=Path.Combine(Request.MapPath("~/"),fileName);
with the below instruction
var fileName = Path.GetFileName(file.FileName);
var imagePath = Path.Combine(Request.MapPath("~/"), fileName);
file.SaveAs(imagePath);
........
Cordially
Related
I am using the System.Net.WebClient.DownloadStringTaskAsync async method to upload a web page content and process it or just save it on my local folder. Everything is fine but when the web page contains some special characters like ™ or ®, they are not getting downloaded. Am I missing something here?
String contentToScrapeURL = "https://www.naylornetwork.com/aaho-advertorial/newsletter.asp?issueID=89542";
Boolean success = true;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}
Found it, or remembered it.
I did set the System.Net.WebClient.Encoding to Encoding.UTF8
So this below is the updated code
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Encoding = Encoding.UTF8;
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}
Am running the project on the visual studio 2015, When I tried to read the PDF its giving me the following error;
Access to the path 'E:\FILE\FILEUPLOAD\InnerFile\File' is denied.
Function Defination
var cd = new System.Net.Mime.ContentDisposition { FileName = "PDF.pdf", Inline = true };
string contentType = MimeMapping.GetMimeMapping("PDF.pdf");
Response.AppendHeader("Content-Disposition", cd.ToString());
var innerPath = "InnerFile/File" ;
FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath);
return File(bytes, contentType);
NOTE:
Given Full permission to user
Physically File Exists
I dont understand what to do now please help!
Your FileInfo instance indeed references 'E:\FILE\FILEUPLOAD\InnerFile\File\PDF.pdf':
FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf");
but when trying to read the file contents you forgot the file name and only use the path 'E:\FILE\FILEUPLOAD\InnerFile\File':
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath);
Thus, also add the file name for reading all file bytes:
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath + "/PDF.pdf");
Furthermore, as others have mentioned in comments, you should really use Path.Combine to glue path parts together, not simple string concatenation...
Try using FileStream instead of byte array for reading the pdf file.
FileStream templateFileStream = File.OpenRead(filePath);
return templateFileStream;
Also check (through code) if user has write permission to directory or path:
public static bool HasUserWritePermission(String path, String NtAccountName)
{
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
Boolean hasPermission = false;
//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
//If we find one that matches the identity we are looking for
if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase))
{
//Cast to a FileSystemAccessRule to check for access rights
if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
{
hasPermission = true;
}
else
{
hasPermission = false;
}
}
}
return hasPermission;
}
I am working on an ASP .net webpage which receives a form which is posted to it. The posted form has three as well.
filename = uploadFile(HttpContext.Current.Request.Files["file1"], path);
This is the code through which i upload a file to my server. And this is the code of the function.
public string uploadFile(HttpPostedFile file, string dest)
{
string filename = file.FileName;
string path = Server.MapPath(dest);
String extension = Path.GetExtension(file.FileName);
filename = filename.Replace(extension, "");
filename = filename.Replace(".", "");
filename = System.DateTime.Now.ToString("ddMMyyyyhhmmss") + filename + extension;
string savepath = path + "/" + filename;
file.SaveAs(savepath);
return filename;
}
The problem is I am not able to check if file1 from the posted form actually has file. Is it possible?
Use the FileUpload control in conjunction with the HasFile property:
FileUpload.HasFile Property
If you have to do it that way, you can simply check if the ContentLength is greater than zero.
I have a arrav string like this:
string[] imgList = new[] { "/Images/10000489Back20130827.jpg", "/Images/2F.jpg", "/Images/10000489Front20130827.jpg" };
that contain names of file, contained in an virtaul directory.
If this parameteres I assigned to an ImageUrl, the image is displayed. In the detail of the pages show the propertie like this:
src="/Images/1F.jpg"
But when I try to looking for the files in specific directory all the files and assigned to an ImageUrl rpoperties, the images it's not displayed. I note that the path retrieve complete, and not a reference of the virtaul directory
string path = "/Images"; ///Obtener el path virtual
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.jpg");
imgList = files.Where(x => x.FullName.Contains(clientNumber)).Select(x => x.FullName).ToList().ToArray();
I retrieve this path:
src="C:/Images/1F.jpg"
How can I get only the virtual path with the name of the file using DirectoryInfo class?
try this:
string path = "/Images";
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(path));
I resolved it:
Instead to pass the full path:
x.FullName
I concatenate the virtual path with the file name.
path + x.Name
Example
imgList = files.Where(x => x.FullName.Contains(clientNumber)).Select(x => path + x.Name).ToList().ToArray();
Show Image In Virtual Path Like (C:\Users\User\Desktop\Signature.png) : Its Working
I used Try Catch To Avoid Error
Cliend Side :
asp:Image runat="server" ID="Image1" />
Server Side :
try
{
Byte[] bytes = System.IO.File.ReadAllBytes(#"C:\Users\User\Desktop\Signature.png");
Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.Visible = true;
}
catch (Exception e)
{
}
I am using the below code to Upload an Image file to a SharePoint Document Library. The code works fine locally but once deployed to server, i get the Exception as file not found.
String fileToUpload = FlUpldImage.PostedFile.FileName; //#"C:\Users\admin.RSS\Desktop\Photos\me_skype.jpg";
String documentLibraryName = "SiteAssets";
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = web.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = CheckStringNull(txtFirstName.Text) + CheckStringNull(txtLastName.Text) + CheckDateNull(txtDOB) + System.IO.Path.GetFileName(fileToUpload); ;
if (fileName.Contains('/'))
{
fileName = fileName.Replace("/", "");
}
if (fileName.Contains(':'))
{
fileName = fileName.Replace(":", "");
}
FileStream fileStream = File.OpenRead(fileToUpload);
//Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
string url = site.ToString() + "/" + spfile.ToString();
if (url.Contains("="))
{
url = url.Split('=')[1];
}
//Commit
myLibrary.Update();
The string fileupload contains URL as C:\Users\admin.RSS\Desktop\Photos\me.jpg This URL is actually the client system and the server side code throws exception as file not found. How to handle this issue?
UPDATE:
I removed the lines of code that checks if the file exists and now i get the exeption on FileStream fileStream = File.OpenRead(fileToUpload); as c:\windows\system32\inetsrv\20120605_133145.jpg cold not be found
Kindly help. Thank You
if (this.fuAvatarUpload.HasFile && this.fuAvatarUpload.PostedFile.FileName.Length > 0)
{
string extension = Path.GetExtension(file.FileName).ToLower();
string mimetype;
switch (extension)
{
case ".png":
case ".jpg":
case ".gif":
mimetype = file.ContentType;
break;
default:
_model.ShowMessage("We only accept .png, .jpg, and .gif!");
return;
}
if (file.ContentLength / 1000 < 1000)
{
Image image = Image.FromStream(file.InputStream);
Bitmap resized = new Bitmap(image, 150, 150);
byte[] byteArr = new byte[file.InputStream.Length];
using (MemoryStream stream = new MemoryStream())
{
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byteArr = stream.ToArray();
}
file.InputStream.Read(byteArr, 0, byteArr.Length);
profile.ImageUrl = byteArr;
profile.UseGravatar = false;
profileService.UpdateProfile(profile);
this._model.ShowApprovePanel();
}
else
{
_model.ShowMessage("The file you uploaded is larger than the 1mb limit. Please reduce the size of your file and try again.");
}
}
Saving the file physically onto server and than working on the same helped me resolve my issue.