Hello I have a method in my controller that looks like this.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImage(int? id)
{
if (id == null)
return HttpNotFound();
Component c = db.Components.Find((int)id);
HttpPostedFileBase photo = Request.Files["image"];
if (photo != null && photo.ContentLength > 0)
{
var filename = IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg";
photo.SaveAs(filename);
c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
db.SaveChanges();
}
else
{
if (Request["imageurl"] != null && Request["imageurl"].Length > 0)
{
// download this file
WebClient wc = new WebClient();
wc.DownloadFile(Request["imageurl"], IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg");
c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
db.SaveChanges();
}
}
HttpPostedFileBase reference = Request.Files["referencefile"];
if (reference != null && reference.ContentLength > 0)
{
// Upload the origin file and create a URL
var filename = IGT.contentPath + "\\uploads\\Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
reference.SaveAs(filename);
c.Reference_Url = IGT.baseUrl + "/Content/uploads/Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
db.SaveChanges();
}
return RedirectToAction("Edit", new { id = id });
}
But currently when it gets to
photo.SaveAs(filename);
I receive the error message
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\chris\Source\Repos\inventory2.0\PIC_Program_1.0\Content\images\Components\498.jpg
How can I make a try catch block so that if the folder doesn't exist in IIS Express, it will create it?
You could use the below code to create directory programmatically:
if (!Directory.Exists(appDataPath)) {
Directory.CreateDirectory(appDataPath);
}
and use directory.SetAccessControl(security); method to set the permission to that folder.
please refer the below links for more detail:
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.createdirectory?view=netframework-4.8
C# Creating directory and setting the permissions
https://www.kunal-chowdhury.com/2016/02/folder-permission.html
Can you try this code:
if (!System.IO.Directory.Exists("your folder")) {
System.IO.Directory.CreateDirectory("Your Folder");
}
Also, make sure your IIS user has a read/write access to that folder directory.
Related
Here is all I want to do: Every time the button is clicked, an openfile dialog is opened, the user clicks on a picture, then this picture is copied to a specific folder and renamed to a number. Every picture's name in this folder should be a number, but they must all be different. My code so far:
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
int i = 0;
if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
MessageBox.Show(picturedir + "\\" + i.ToString() + ".png" + ".....Already Exists.");
}
else if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == false)
{
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course here, the first picture is copied and renamed to "0.png" but the next pictures are not copied at all, because the "if" gives true. Any ideas ? Thanks.
You could do this:
...
int i = 0;
while (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
// I wouldn't show that message each time, gonna get pretty old for lots of pics!
}
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
...
If you want the next number, you can enumerate the existing files, find the maximum number now in use and add 1. Something like:
var files = Directory.EnumerateFiles(myCurrentDirectory, "*.png");
var fileNumStrings = from file in files select Path.GetFileNameWithoutExtension(file);
var max = 0;
foreach (var fileNumString in fileNumStrings)
{
if (int.TryParse(fileNumString, out var filenum))
{
if (filenum > max)
{
max = filenum;
}
}
}
var nextNum = max + 1;
I have been looking for some time now and have not been able to find this. How can I set my program up to write or update a file from multiple users but only one group is allowed to open the read what is in the folder?
class Log_File
{
string LogFileDirectory = #"\\server\boiseit$\TechDocs\Headset Tracker\Weekly Charges\Log\Log Files";
string PathToXMLFile = #"\\server\boiseit$\scripts\Mikes Projects\Headset-tracker\config\Config.xml";
string AdditionToLogFile = #"\Who.Did.It_" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ".txt";
XML XMLFile = new XML();
public void ConfigCheck()
{
if (!File.Exists(PathToXMLFile))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
}
}
public void CreateLogFile()
{
if (Directory.GetFiles(LogFileDirectory).Count() == 0)
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else if (!File.Exists(XMLFile.readingXML(PathToXMLFile)))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else
{
FileInfo dateOfLastLogFile = new FileInfo(XMLFile.readingXML(PathToXMLFile));
DateTime dateOfCreation = dateOfLastLogFile.CreationTime;
if (dateOfLastLogFile.CreationTime <= DateTime.Now.AddMonths(-1))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
}
}
public void CreateFileOrAppend(string whoDidIt)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetStore((IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User), null, null))
{
using (StreamWriter myWriter = new StreamWriter(XMLFile.readingXML(PathToXMLFile), true))
{
if (whoDidIt == "")
{
}
else
{
myWriter.WriteLine(whoDidIt);
}
}
}
}
This is my path where it needs to go. I have the special permission to open and write to the folder but my co workers do not. I am not allow to let them have this permission.
If I where to set up a database how would i change this code
LoggedFile.CreateFileOrAppend(Environment.UserName.ToUpper() + "-" + Environment.NewLine + "Replacement Headset To: " + AgentName + Environment.NewLine + "Old Headset Number: " + myDatabase.oldNumber + Environment.NewLine + "New Headset Number: " + HSNumber + Environment.NewLine + "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine);
I need it to pull current user, the agents name that is being affected the old headset and the new headset, and the time it took place.
While you create file, you have to set access rules to achieve your requirements. .
File.SetAccessControl(string,FileSecurity)
The below link has example
https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol(v=vs.110).aspx
Also the "FileSecurity" class object, which is an input parameter, has functions to set access rules, including group level control.
Below link has example
https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity(v=vs.110).aspx
This question will be opened under a new question since I am going to take a different route for recording the data I need Thank you all for the help
I have a website where photographers can upload photos. The site is being hosted on an shared azure web app and The photos and thumbnails of the photos are uploaded to Azure Blob storage and a record is written to the db. Photographers can upload potentially up to 700mb of photos at a time.
My problem
I had a synchronous method for the upload that A) took ages to run and B) failed with the "There is not enough space on disk" error message. I'm guessing this is because the temp folder for a Azure shared web app is restricted to 200mb.
I tried to implement a Asynchronous method to help speed up the upload but it completes the first photo successfully (ie blobs and db records exist) and then It appears to just hang. This is my first attempt at writing an asynchronous method.
I also don't know how to fix the temp folder size issue.
My calling method
public static async Task<Tuple<bool, string>> UploadAsync(HttpPostedFileBase[] photos, Bookings booking, string photoType, ApplicationUser user)
{
// For each file to be uploaded
foreach (HttpPostedFileBase file in photos)
{
try
{
await UploadPhotoFromFileAsync(file, user, booking.BookingsId, photoType);
}
catch (Exception ex)
{
// Not Implemented
}
}
return new Tuple<bool, string>(true, "Photos uploaded successfully");
}
My Photo Upload method
public static Task UploadPhotoFromFileAsync(HttpPostedFileBase file, ApplicationUser user, int bookingId, string photoType)
{
return Task.Run(() =>
{
using (ApplicationDbContext dbt = new ApplicationDbContext())
{
Bookings booking = dbt.Bookings.Find(bookingId);
// Craete a new record in the UserFiles table
Photos photo = new Photos();
photo.BookingsId = booking.BookingsId;
photo.PhotoType = photoType;
photo.FileName = Path.GetFileName(file.FileName);
string confirmedDate = string.Empty;
if (booking.ConfirmedDate.HasValue)
{
DateTime actualConfirmedDate = booking.ConfirmedDate.Value;
confirmedDate = actualConfirmedDate.Year.ToString() + actualConfirmedDate.Month.ToString() + actualConfirmedDate.Day.ToString();
}
string blobName = string.Empty;
string blobThumbName = string.Empty;
if (photoType == "SamplePhoto")
{
// Get the count of the sample photos in the gallery
List<Photos> samplePhotos = dbt.Photos.Where(m => m.BookingsId == booking.BookingsId && m.PhotoType == "SamplePhoto").ToList();
blobName = "TS_" + booking.location.Location.Replace(" ", "") + "_" + booking.BookingsId.ToString() + "_" + confirmedDate + "_" + (samplePhotos.Count).ToString() + "_sample" + Path.GetExtension(file.FileName);
blobThumbName = "TS_" + booking.location.Location.Replace(" ", "") + "_" + booking.BookingsId.ToString() + "_" + confirmedDate + "_" + (samplePhotos.Count).ToString() + "_sample_thumb" + Path.GetExtension(file.FileName);
}
else
{
// Get the count of the sample photos in the gallery
List<Photos> photos = dbt.Photos.Where(m => m.BookingsId == booking.BookingsId && m.PhotoType == "GalleryPhoto").ToList();
blobName = "TS_" + booking.location.Location.Replace(" ", "") + "_" + booking.BookingsId.ToString() + "_" + confirmedDate + "_" + (photos.Count).ToString() + Path.GetExtension(file.FileName);
blobThumbName = "TS_" + booking.location.Location.Replace(" ", "") + "_" + booking.BookingsId.ToString() + "_" + confirmedDate + "_" + (photos.Count).ToString() + "_thumb" + Path.GetExtension(file.FileName);
}
// Create the Thumbnail image.
CloudBlobContainer thumbnailBlobContainer = _blobStorageService.GetCloudBlobContainer("thumbnails");
if (CreateThumbnailImageFromHttpPostedFileBase(file, blobThumbName, photo))
{
photo.ThumbnailBlobName = blobThumbName;
photo.ThumbnailBlobUrl = thumbnailBlobContainer.Uri + "/" + blobThumbName;
}
CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer("photos");
photo.BlobName = blobName;
photo.BlobUrl = blobContainer.Uri + "/" + blobName;
photo.DateCreated = DateTime.Now;
photo.CreatedBy = user.Id;
dbt.Photos.Add(photo);
dbt.SaveChanges();
booking.Photos.Add(photo);
dbt.SaveChanges();
//Upload to Azure Blob Storage
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
blob.UploadFromStream(file.InputStream);
}
});
}
The Azure Storage library includes Async-methods and you should take advantage of those. And instead of wrapping your controller method with Task.Run, you can use ASP.NET MVC's built-in async-capabilities.
So, first, make the controller's method async:
public async Task<ContentResult> UploadPhotoFromFileAsync...
Then remove all the Task.Runs.
Lastly, call Azure Storage Library's async-methods:
var blob = blobContainer.GetBlockBlobReference(blobName);
await blob.UploadFromStreamAsync(file.InputStream);
The problem was actually being caused by the request length set in the Web.Config. It wasn't high enough to allow for the size of the photos being uploaded. I simply added the following code to the Web.Config.
<system.web>
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" executionTimeout="900" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
I am working on a website, in which users can upload file/photos and for uploading i am using uploadify control
I am adding loggedin userID and Current day and year to the file then saving it,I've save the userID in a Session(Session["userid"]), its working fine on IE and chrome but when i run it from firefox, it is showing Session["userid"]= null and because of this its not uploading the file, below is my code to uploading file
public string UploadFile(HttpPostedFileBase fileData)
{
try
{
if (fileData != null && fileData.ContentLength > 0)
{
var root = AppDomain.CurrentDomain.BaseDirectory + #"Uploads\File\";
var filname = fileData.FileName.Split('.')[0] + "_" + Session["userid"].ToString() + "_" + DateTime.Now.Day + DateTime.Now.Year + "." + fileData.FileName.Split('.')[1];
var path = root + Path.GetFileName(filname);
//if (System.IO.File.Exists(path))
// return "Upload Failed! A file with this name already exists.";
fileData.SaveAs(path);
return "1";
}
return "file not selected.";
}
catch (Exception ex)
{
throw ex;
}
}
Although the user is loggedin but still its showing the session null
Maybe you have cookies disabled in your firefox
How to change file name on upload ?
I have such code :
<%# WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
using System.IO;
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context) {
HttpPostedFile oFile = context.Request.Files["Filedata"];
string newFileName1 = HttpContext.Current.Server.MapPath(#context.Request["orderID"]);
string newFileName2 = HttpContext.Current.Server.MapPath(#context.Request["productCombinationString"]);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + oFile.ContentType;
} else {
newName = newFileName1 + oFile.ContentType;
}
string sDirectory = HttpContext.Current.Server.MapPath(#context.Request["folder"]);
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
context.Response.Write("1");
}
public bool IsReusable {
get { return false; }
}
}
And if i change oFile.Filename to newName it does not work ... what is the problem ? :)
Thank you
You can pass your Custom File Name along with Directory to SaveAs Method
oFile.SaveAs(sDirectory + "/" + "abc");
try:
// Get the extension of the uploaded file.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + extension ;
} else {
newName = newFileName1 + extension ;
}
oFile.SaveAs(sDirectory + "/" + newName );
I haven't tried this code but I do want to point out two things of from the original code:
The first is this order of operations:
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
I believe it should be this instead. In the above sequence, there is a potential edge case of saving into a non-existing folder. This ensures that the folder is created:
if (!Directory.Exists(sDirectory))
{
Directory.CreateDirectory(sDirectory);
}
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
The other thing is that you might be running into issues with / as the path separator. I think it should be much safer to do something like:
var saveLocation = Path.Combine(sDirectory, oFile.FileName);
oFile.SaveAs(saveLocation);
I hope this helps!
Here is an example i used when saving an image look at the save as section
////saving file in the physical folder;
FileUpload FileUpload1 = file_Image;
string virtualFolder = "~/Resourceimages/";
string physicalFolder = HostingEnvironment.MapPath(virtualFolder);
string PhotoName = ((string)Session["UserName"] + (string)Session["UserSurname"]);
FileUpload1.SaveAs(physicalFolder + PhotoName + FileUpload1.FileName);
string location = virtualFolder + PhotoName + FileUpload1.FileName;
webservice.UpdateResourceImage((int)Session["UserID"], location);
lbl_Result.Text = "Your file " + FileUpload1.FileName + " has been uploaded.";
Image1.Visible = true;
Image1.ImageUrl = location;
string uploadFolder = Request.PhysicalApplicationPath + "UploadFile\\";
if (FileUpload1.HasFile)
{
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(uploadFolder + "Test"+ extension);
Label1.Text = "File uploaded successfully as: " + "Test"+ extension;
}
else
{
Label1.Text = "First select a file.";
}
private string UpdateFilename(string filename)
{
try
{
filename = Server.HtmlEncode(FUJD.FileName);
string extension = System.IO.Path.GetExtension(filename);
filename = filename.Replace(extension, "");
return filename + '-' + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
}
catch (Exception ex)
{
throw ex;
}
}