File not found exception once deployed to Server - asp.net

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.

Related

Recieve/Accept file in WEBDAV from httpwebrequest POST or PUT in asp.net

Suppose I have sample Upload file method like this in POStFile.aspx.
This method POST file (upload file) to http WEBDAV url.
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) {
log.Debug(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) {
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try {
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
} catch(Exception ex) {
log.Error("Error uploading file", ex);
if(wresp != null) {
wresp.Close();
wresp = null;
}
} finally {
wr = null;
}
}
From here
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
HttpUploadFile("http://your.server.com/upload",
#"C:\test\test.jpg", "file", "image/jpeg", nvc);
Question 1 : Shouldn't the url should be like "http://your.server.com/upload.aspx" instead of "http://your.server.com/upload"
If I give url like "http://your.server.com/upload" then i get 405 error method not found.
So it should point to any page.
Question 2 : How should I receive the post and save the file in upload.aspx.
Can the file directly uploaded to remote server without any receiving
page ?
This question was about "File transfer to WEBDAV http URL using or POST or PUT method"
Above is sample POST method.Similarly there can by PUT method which is little different from POST method.
Question 1 : Shouldn't the url should be like "http://your.server.com/upload.aspx" instead of "http://your.server.com/upload"
For novice man like me, main confusion is URL.It entirely depend upon "How WEBDAV server want to receive POST or PUT method ?"
I think for POST method ,there should be one receiving page which accept file and other parameters from POSTfile page and save the file to disk.
I don't know about .net code but WEB API has inbuilt feature which can parse data like "multipart/form-data; boundary=---------------------------8d60ff73d4553cc"
Below code is just sample code,
[HttpPost]
public async Task<FileUploadDetails> Post()
{
// file path
var fileuploadPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
////
var multiFormDataStreamProvider = new MultiFileUploadProvider(fileuploadPath);
// Read the MIME multipart asynchronously
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
string uploadingFileName = multiFormDataStreamProvider
.FileData.Select(x => x.LocalFileName).FirstOrDefault();
// Files
//
foreach (MultipartFileData file in multiFormDataStreamProvider.FileData)
{
Debug.WriteLine(file.Headers.ContentDisposition.FileName);
Debug.WriteLine("File path: " + file.LocalFileName);
}
// Form data
//
foreach (var key in multiFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multiFormDataStreamProvider.FormData.GetValues(key))
{
Debug.WriteLine(string.Format("{0}: {1}", key, val));
}
}
//Create response
return new FileUploadDetails
{
FilePath = uploadingFileName,
FileName = Path.GetFileName(uploadingFileName),
FileLength = new FileInfo(uploadingFileName).Length,
FileCreatedTime = DateTime.Now.ToLongDateString()
};
return null;
}
So url in POSTFile.aspx page should point to API method in this case,
"http://your.server.com/api/fileUpload"
where fileUpload is api controller name.
If you are using HTTP PUT method then
i) you want to receive it in pro grammatically handle it.Write PUT method similar to POST method in api class.
ii) you want to directly save the file to folder using PUT method.
so URL in this case can be,
"http://your.server.com/Imagefolder"
Yes this can be done with extra IIS setting.
Create virtual directory in Target folder,beside few other thing.

System.IO.File.ReadAllBytes Access to the path denied

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;
}

Upload Image from URI to Azure BLOB

I'd like to upload images from an uri postet to an asp.net mvc5 controller to azure blob storage. I already got it working with HttpPostedFileBase, like this. Can I somehow get the memory stream from an image uri?
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
var imgFile = System.Drawing.Image.FromStream(hpf.InputStream, true, true);
CloudBlockBlob blob = coversContainer.GetBlockBlobReference("img.jpg");
MemoryStream stream = new MemoryStream();
imgFile.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
blob.UploadFromStream(stream);
So this is how I managed to get it done:
public static Image DownloadRemoteImage(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception)
{
return null;
}
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download it
Stream inputStream = response.GetResponseStream();
Image img = Image.FromStream(inputStream);
return img;
}
else
{
return null;
}
}
This code snipped was taken and modified from this question's answer:
Download image from the site in .NET/C#

How do I write in log file from start instead append it to end of file

I have following code for log file
which will create a log file and write log into that file.
But I want to write that log into file in DESC order
so that recent log text will come first.
string FilePath = Path(MYLOG.txt");
if (!File.Exists(FilePath))
{
byte[] fileBytes = null;
fileBytes = Encoding.GetEncoding(1252).GetBytes("My Log -\n");
using (Stream streamToWrite = File.Create(FilePath))
{
streamToWrite.Write(fileBytes, 0, fileBytes.Length);
streamToWrite.Flush();
}
I mean want to write new content from start not to end of the file
I think this will do
string currentContent = String.Empty;
if (File.Exists(filePath))
{
currentContent = File.ReadAllText(filePath);
}
File.WriteAllText(filePath, newContent + currentContent );

Download File Servlet - File Content contains binary

I had tried to develop a servlet that allow user to download file but it allow user to download the file but the file content contains binary garbage and not human readable. May I know what could be the reason ?
Code
int length = -1, index = 0;
byte[] buffer = null;
String attachmentPath = null, contentType = null, extension = null;
File attachmentFile = null;
BufferedInputStream input = null;
ServletOutputStream output = null;
ServletContext context = null;
attachmentPath = request.getParameter("attachmentPath");
if (attachmentPath != null && !attachmentPath.isEmpty()) {
attachmentFile = new File(attachmentPath);
if (attachmentFile.exists()) {
response.reset();
context = super.getContext();
contentType = context.getMimeType(attachmentFile.getName());
response.setContentType(contentType);
response.addHeader("content-length", String.valueOf(attachmentFile.length()));
response.addHeader("content-disposition", "attachment;filename=" + attachmentFile.getName());
try {
buffer = new byte[AttachmentTask.DEFAULT_BUFFER_SIZE];
input = new BufferedInputStream(new FileInputStream(attachmentFile));
output = response.getOutputStream();
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
index += length;
// output.write(length);
}
output.flush();
input.close();
output.close();
} catch (FileNotFoundException exp) {
logger.error(exp.getMessage());
} catch (IOException exp) {
logger.error(exp.getMessage());
}
} else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IOException exp) {
logger.error(exp.getMessage());
}
}
It is relate to writing file as binary or text mode or browser settings?
Please help.
Thanks.
The problem is not in the code given so far. You're properly using InputStream/OutputStream instead of a Reader/Writer to stream the file.
The cause of the problem is more likely in the way how you created/saved the file. This problem will manifest when you've used a Reader and/or Writer which is not been instructed to use the proper character encoding for the characters being read/written. Perhaps you're creating an upload/download service and the fault was in the upload process itself?
Assuming that the data is in UTF-8, you should have created the reader as follows:
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8"));
and the writer as follows:
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
But if you actually don't need to manipulate the stream on a per-character basis, but just wanted to transfer the data unmodified, then you should actually have used InputStream/OutputStream all the time.
See also:
Unicode - How to get the characters right?

Resources