read multiple uploaded files in c# - c#

i am develop a project that can save and delete uploaded files from local system. here is the sample code and i am using fileupload asp-control in asp.net c#
List<AttachmentModel> attachmentList = new List<AttachmentModel>();
if (fuAttachment.HasFiles)
{
foreach (HttpPostedFile uploadedFile in fuAttachment.PostedFiles)
{
attachment.AttachmentType = "Attachment";
attachment.FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
uploadedFile.SaveAs(Path.Combine(Server.MapPath(#"~/Attachments/" + uploadedFile)));
attachmentList.Add(attachment);
}
}
objEL.AttachmentList = attachmentList;
i am trying to upload multiple files( >=2 files). but i am able to read only one file that is selected first..
so then i have changed one line
attachment.FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
to
attachment.FileName = uploadedFile.FileName;
but with this i am getting the whole path of the file as
"C:\Users\ThirupathiReddy\Downloads\PSK_logo.jpg"
i just want to read the file name ...
thank you..

Try:
var fullFilename = #"C:\Users\ThirupathiReddy\Downloads\PSK_logo.jpg";
var fileInfo = new FileInfo(fullFilename );
var filename = fileInfo.Name;

Related

How to get the file extension of a downloaded file in One Drive Graph API

I have written a console app in c# following this tutorial: https://learn.microsoft.com/en-gb/training/modules/msgraph-access-file-data/3-exercise-access-files-onedrive
Now when I download a file from my OneDrive via the console app using Microsoft Graph API, all the files get downloaded in type "File". However, the files are of type "Docx".
So how do I ensure that the files get downloaded in their original extension format? (.docx, .ppt, .csv, etc.)
var fileId = "01HLTXGBVIH3R6ILTKF5FKB2EMZKFG3MQ6";
var request = client.Me.Drive.Items[fileId].Content.Request();
var stream = request.GetAsync().Result;
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "driveItem_" + fileId + ".file");
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);
Make a request to get file and read name property which represents the name of the item (filename and extension).
var fileId = "01HLTXGBVIH3R6ILTKF5FKB2EMZKFG3MQ6";
// make a request to get the file
var file = client.Me.Drive.Items[fileId].Request().GetAsync().Result;
var fileName = file.Name;
var request = client.Me.Drive.Items[fileId].Content.Request();
var stream = request.GetAsync().Result;
// create a file with the same name
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);

Storing and getting back files from MongoDB

I am working on c# .Net 4.5
I have to upload some files on MongoDB and in other module, I have to get them back based on metadata.
for that I am doing like below,
static void uploadFileToMongoDB(GridFSBucket gridFsBucket)
{
if (Directory.Exists(_sourceFilePath))
{
if (!Directory.Exists(_uploadedFilePath))
Directory.CreateDirectory(_uploadedFilePath);
FileInfo[] sourceFileInfo = new DirectoryInfo(_sourceFilePath).GetFiles();
foreach (FileInfo fileInfo in sourceFileInfo)
{
string filePath = fileInfo.FullName;
string remoteFileName = fileInfo.Name;
string extension = Path.GetExtension(filePath);
double fileCreationDate = fileInfo.CreationTime.ToOADate();
GridFSUploadOptions gridUploadOption = new GridFSUploadOptions
{
Metadata = new BsonDocument
{{ "creationDate", fileCreationDate },
{ "extension", extension }}
};
using (Stream fileStream = File.OpenRead(filePath))
gridFsBucket.UploadFromStream(remoteFileName, fileStream, gridUploadOption);
}
}
}
and downloading,
static void getFileInfoFromMongoDB(GridFSBucket bucket, DateTime startDate, DateTime endDate)
{
double startDateDoube = startDate.ToOADate();
double endDateDouble = endDate.ToOADate();
var filter = Builders<GridFSFileInfo>.Filter.And(
Builders<GridFSFileInfo>.Filter.Gt(x => x.Metadata["creationDate"], startDateDoube),
Builders<GridFSFileInfo>.Filter.Lt(x => x.Metadata["creationDate"], endDateDouble));
IAsyncCursor<GridFSFileInfo> fileInfoList = bucket.Find(filter); //****
if (!Directory.Exists(_destFilePath))
Directory.CreateDirectory(_destFilePath);
foreach (GridFSFileInfo fileInfo in fileInfoList.ToList())
{
string destFile = _destFilePath + "\\" + fileInfo.Filename;
var fileContent = bucket.DownloadAsBytes(fileInfo.Id); //****
File.WriteAllBytes(destFile, fileContent);
}
}
in this code (working but) I have two problems which I am not sure how to fix.
If i have uploaded a file and I upload it again, it actually gets
uploaded. How to prevent it?
Ofcourse both uploaded files have different ObjectId but while uploading a file I will not be knowing that which files are already uploaded. So I want a mechanism which throws an exception if i upload already uploaded file. Is it possible? (I can use combination of filename, created date, etc)
If you have noticed in code, actually i am requesting to database server twice to get one file written on disk, How to do it in one shot?
Note lines of code which I have marked with "//****" comment. First I am querying into database to get fileInfo (GridFSFileInfo). I was expecting that I could get actual content of file from this objects only. But I didnot find any related property or method in that object. so I had to do var fileContent = bucket.DownloadAsBytes(fileInfo.Id); to get content. M I missing something basic here ?

This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked

I am trying to browse and upload a file from client to server using Angular Js and WEB API.I used Input file type for user to select file and post the file to WEB API. In web API, I am getting following error "This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked."
I am using the following code:-
public IHttpActionResult UploadForm()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = System.Web.HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return Json("Document Saved");
}
I get this error when i tried to get files from HTTP request... should I update anything in web config??
Please help me to resolve this issue..
try this it work fine for me.
//get the root folder where file will be store
string root = HttpContext.Current.Server.MapPath("~/UploadFile");
// Read the form data.
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.FileData.Count > 0 && provider.FileData[0] != null)
{
MultipartFileData file = provider.FileData[0];
//clean the file name
var fileWithoutQuote = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2);
//get current file directory on the server
var directory = Path.GetDirectoryName(file.LocalFileName);
if (directory != null)
{
//generate new random file name (not mandatory)
var randomFileName = Path.Combine(directory, Path.GetRandomFileName());
var fileExtension = Path.GetExtension(fileWithoutQuote);
var newfilename = Path.ChangeExtension(randomFileName, fileExtension);
//Move file to rename existing upload file name with new random filr name
File.Move(file.LocalFileName, newfilename);
}
}
I also had the same problem. And the solution by #Jean did not work for me.
I need to upload some CSV file and had to use it in the controller.
In Javascript, I used Fetch API to upload the csv file.
But, in the controller, I used this code:
[HttpPost]
[CatchException]
public bool ImportBundlesFromCsv()
{
var a = Request.Content.ReadAsByteArrayAsync();
//convert to Stream if needed
Stream stream = new MemoryStream(a.Result); // a.Result is byte[]
// convert to String if needed
string result = System.Text.Encoding.UTF8.GetString(a.Result);
// your code
return true;
}
This worked for me. Hope this helps!

Removing the file with same name, extension doesn't matter

I have some files in "~Content/Documents" folder which holds every uploaded file. In my case the user can only upload one file.
I have done the uploading part where the user can upload his file.
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fullpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Documents");
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
}
My problem is:
User can upload either ".doc", ".docx", ".xls", ".xlsx", or ".pdf" format files.
Now when the user upload the file of ".doc" format it is uploaded to the folder. Later the same user can upload the file of ".pdf" format which is also uploaded to the folder. That means the user can upload two files.
Now what I want to do is:
When a specific user uploads his document:
->search whether the document uploaded by the user is in that folder or not. i.e. the specific filename with different extension exists or not.
->if the filename already exists with different extension then remove that file and upload the new file.
Try this, Just another way; If your filename is "document"
string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
System.IO.File.Delete(f);
}
So your code would be;
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fullpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Documents");
//deleting code starts here
string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
System.IO.File.Delete(f);
}
//deleting code ends here
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
}
Something like this should do the trick
var files = new DirectoryInfo(fullpath).GetFiles();
var filesNoExtensions = files.Select(a => a.Name.Split('.')[0]).ToList();
//for below: or 'document' if that's what you rename it to be on disk
var fileNameNoExtension = fileName.Split('.')[0];
if (filesNoExtensions.Contains(fileNameNoExtension))
{
var deleteMe = files.First(f => f.Name.Split('.')[0] == fileNameNoExtension);
deleteMe.Delete();
}
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
Get the filename of the new file without extension, then loop through all the filenames in the folder where it will be uploaded to and check if the name already exists. If so, delete the old an upload, else upload.
var info = new FileInfo("C:\\MyDoc.docx");
var filename = info.Name.Replace(info.Extension, "");
var files = Directory.GetFiles("YOUR_DIRECTORY").Select(f => new FileInfo(f).Name);
if (files.Any(file => file.Contains(filename)))
{
//Delete old file
}
//Upload new file

changing name of uploaded images

What I am trying to achieve is changing the name of uploaded images to a somewhat unique string.
I have created an image gallery which is populated dynamically by database. The gallery is working fine except, that files stored in the database will be problematic if an image with the same name is uploaded!
Code in the controller for file upload:
string AdvertImage = picture1.FileName;
advert.AdvertImage = AdvertImage;
var image1Path = Path.Combine(Server.MapPath("~/Content/Images"), AdvertImage);
picture1.SaveAs(image1Path);
The code below is what I am working on
string BackImage = DateTime.Now.ToString("yyyyMMddhhmmssfffffff");
caradvert.BackImage = BackImage;
var image3Path = Path.Combine(Server.MapPath("~/Content/CarImages"), BackImage);
picture3.SaveAs(image3Path);
I have managed to create a unique file name thou it is not appending .jpg to the end of the image.
Any help or advice on the subject welcome
Try this:
//save file in folder
if (FileUpload1.PostedFile.ContentType.ToLower().StartsWith
("image") && FileUpload1.HasFile)
{
string savelocation = Server.MapPath("savedImages/");
string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
//creating filename to avoid file name conflicts.
string fileName = Guid.NewGuid().ToString();
//saving file in savedImage folder.
string savePath = savelocation + fileName + fileExtention;
FileUpload1.SaveAs(savePath);
}

Categories