I am trying to upload a .png file using below source code. These codes are executed successfully without having any error and Directory also created as per the mentioned path. But file is not being uploaded on that path.
public bool SaveFile(string Filepath, string FileContainer, string FileNewName)
{
IMMAuthenticationManager iMMAuthenticationManager = null;
IConfiguration iConfig = null;
FileUtility FU = new FileUtility(iMMAuthenticationManager, iConfig);
var file = HttpContext.Request.Form.Files[FileContainer];
bool FileData = FU.FileUtilityUpload2(Filepath, file, FileNewName);
return FileData;
}
public bool FileUtilityUpload2(string path, IFormFile file, string FileNewName)
{
if (file != null)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (file.FileName != "")
{
var ext = System.IO.Path.GetExtension(file.FileName);
//uniqueName = Guid.NewGuid().ToString() + ext;
string fileSavePath = Path.Combine(path, FileNewName);
MemoryStream streamfileSavePath = new MemoryStream(Encoding.UTF8.GetBytes(fileSavePath));
file.CopyToAsync(streamfileSavePath);
return true;
}
}
return false;
}
Here value of fileSavePath is C:\\Development\MedicalMonitor\Task\DEMO1001\Task1666027260354.png.
Is there any mistake in the above code?
If you want to use MemoryStream upload file, You can use this code:
public bool FileUtilityUpload2(string path, IFormFile file, string FileNewName)
{
if (file != null)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (file.FileName != "")
{
//var ext = System.IO.Path.GetExtension(file.FileName);
//uniqueName = Guid.NewGuid().ToString() + ext;
using (MemoryStream streamfileSavePath = new MemoryStream())
{
string fileSavePath = Path.Combine(path, FileNewName);
using (var fs = new FileStream(fileSavePath, FileMode.Create, FileAccess.Write))
{
streamfileSavePath.WriteTo(streamfileSavePath);
}
}
return true;
}
}
return false;
}
Or, You can also use the asynchronous method recommended by the Microsoft Docs, it is simpler
public async Task<bool> FileUtilityUpload2(string path, IFormFile file, string FileNewName)
{
if (file != null)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (file.FileName != "")
{
var ext = System.IO.Path.GetExtension(file.FileName);
//uniqueName = Guid.NewGuid().ToString() + ext;
string fileSavePath = Path.Combine(path, FileNewName);
using (var stream = System.IO.File.Create(fileSavePath))
{
await file.CopyToAsync(stream);
}
return true;
}
}
return false;
}
Then in SaveFile:
public bool SaveFile(string Filepath, string FileContainer, string FileNewName)
{
//............
bool FileData = FileUtilityUpload2(Filepath, file, FileNewName).IsCompleted;
return FileData;
}
Related
this code works once in server and after that again we click the submit button server shows "www.example.com can't currently handle this request.
HTTP ERROR 500"
This is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("AboutId,Title,ImagePath,ShortContent,LongContent,RecordStatus,CreatedDate,Seokeywords")] AboutTbl aboutTbl, IFormFile FormFile)
{
if (ModelState.IsValid)
{
//----
string newFileName;
var fileName = ContentDispositionHeaderValue.Parse(FormFile.ContentDisposition).FileName.Trim('"');
int index = fileName.LastIndexOf('.');
string onlyName = fileName.Substring(0, index);
string fileExtension = fileName.Substring(index + 1);
var abtrepo = _aboutTblRepository.FindwithImagePath(fileName);
if (abtrepo != null)
{
newFileName = onlyName + DateTime.Now.ToString("yyyy-MM-ddHHmmtt") + "." + fileExtension;
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "About", newFileName);
aboutTbl.ImagePath = newFileName;
using (System.IO.Stream stream = new FileStream(filePath, FileMode.Create))
{
FormFile.CopyTo(stream);
}
}
else
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "About", FormFile.FileName);
aboutTbl.ImagePath = fileName;
using (System.IO.Stream stream = new FileStream(filePath, FileMode.Create))
{
FormFile.CopyTo(stream);
}
}
//----
byte recordStatus = (byte)Common.CommonEnums.RecordStatus.ACTIVE;
aboutTbl.RecordStatus = (byte?)recordStatus;
DateTime createdDate = DateTime.Now;
aboutTbl.CreatedDate = createdDate;
_aboutTblRepository.CreateAbout(aboutTbl);
_notyf.Success("About added successfully");
return RedirectToAction(nameof(Index));
}
return View(aboutTbl);
}
this is AboutTblRepository
public void CreateAbout(AboutTbl aboutTbl)
{
_context.Add(aboutTbl);
_context.SaveChanges();
}
Interface IAboutTblRepository
public void CreateAbout (AboutTbl aboutTbl);
Recently i found that error
i just removed
var abtrepo = _aboutTblRepository.FindwithImagePath(fileName);
if (abtrepo != null)
{
}
else
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "About", FormFile.FileName);
aboutTbl.ImagePath = fileName;
using (System.IO.Stream stream = new FileStream(filePath, FileMode.Create))
{
FormFile.CopyTo(stream);
}
}
I want to create a folder directory and in that folder, I want to save the image and get the response. but when I check manually using file explorer the folder is not showing.
//take picture code
string DirName = "Sample";
string ImgName = "image.jpg";
string basepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
byte[] imageArray = null;
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
var stream = file.GetStream();
stream.CopyTo(ms);
imageArray = ms.ToArray();
}
}
Stream data = new MemoryStream(imageArray);
if (file == null)
return;
filePath = file.Path;
paths.Enqueue(filePath);
var result = await CrossEDFSTemplate.Current.SaveFile(basepath, DirName,ImgName, filePath);
await DisplayAlert("Succesful", result.ToString(), "ok");
//Directory create code
public async Task<SaveFileResponse> SaveFile(string FolderBasePath, string FolderName, string
FileName, string FileFullPath = null, Stream data = null)
{
SaveCompletionSource = new TaskCompletionSource<SaveFileResponse>();
if (FolderBasePath != null && FolderName != null)
{
var directoryPath = Path.Combine(FolderBasePath, FolderName);
string NemFilePath = Path.Combine(directoryPath, FileName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
if (FileFullPath != null)
{
var imageData = File.ReadAllBytes(FileFullPath);
File.WriteAllBytes(NemFilePath, imageData);
}
else if (data != null)
{
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(NemFilePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
else
{
var ResponseSaved = new SaveFileResponse("There are no items to Save", null, FileName);
SaveFileError(this, ResponseSaved);
SaveCompletionSource.TrySetResult(ResponseSaved);
}
}
else
{
return await SaveCompletionSource.Task;
}
return await SaveCompletionSource.Task;
}
according to this code, the directory is creating but when I manually checking that folder using file explorer the folder is not showing.
The path Environment.SpecialFolder.MyPictures you used to save the file is internal storage.
In Internal Storage, you couldn't see the files without root permission.
But you could use the code to check the file exist or not in the internal storage.
if (File.Exists(filepath))
{
}
If you want to view it, you could use adb tool. Please check the way in link.
How to write the username in a local txt file when login success and check on file for next login?
As am having my ZIP file in the folder and if I click download report button am blocking to download based on my organization policy.
But I need to download this ZIP file from the code how can we achieve this.
The code which I used as below
string[] filenames = Directory.GetFiles(SourceFolder);
ZipFilePath = DestinationFolder + #"\" + ZipFileName;
using (ZipOutputStream s = new
ZipOutputStream(File.Create(ZipFilePath)))
{
s.SetLevel(6);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
if (Path.GetFileName(file).Contains(SubString) || Path.GetFileName(file).Contains("logfile"))
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0,
buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
s.Finish();
s.Close();
}
string DownloadFileName = ZipFilePath;
DownloadFileName = DownloadFileName.Replace("\\", "~");
RadAjaxManager1.ResponseScripts.Add("setTimeout(function(){ document.location.href = 'DownloadHandler.ashx?FileName=" + DownloadFileName + "'; return false; },300);");
The DownloadHandler.ashx page as below
public void ProcessRequest(HttpContext context)
{
try
{
HttpResponse rspns = context.Response;
string FileToDownload = context.Request.QueryString["FileName"];
string FileName = string.Empty;
if (context.Request.QueryString["Name"] != null)
{
FileName = context.Request.QueryString["Name"];
}
if (FileToDownload!=null)
{
FileToDownload = FileToDownload.Replace("~", "\\");
FileName = System.IO.Path.GetFileName(FileToDownload);
}
else
{
//FileName = Convert.ToString(iTAPSession.UserData);
}
rspns.AppendHeader("content-disposition", "attachment; filename=\"" + FileName.Replace(" ", "%20"));
rspns.TransmitFile(FileToDownload);
rspns.End();
}
catch (Exception e)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
am getting the below exception
Based on your organization's access policies, access to this website or download ( http://xxxxxxx/ITAADemo/DownloadHandler.ashx?FileName=D:~ITAADemo~Files~SuperAdmin~bn4wgrusef1xgmjhqokd2yo2~~TextAnalytics~~zipdownload~Report_2018-Jul-19-11-39-31.zip ) has been blocked because the file type "application/zip" is not allowed.
I have to transfer files from FTP to an Azure File Storage. My code works fine, but I'm transferring those files in memory which is not a best practice. So first I read the stream to an Byte array in memory. Then I upload the output to an Azure file storage.
Now I know it's better to do this asynchronicaly. But I don't know if this is possible and how to do it.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using System.Configuration;
using Microsoft.WindowsAzure.Storage.File;
using System.IO;
using Microsoft.Azure;
using System.Net;
namespace TransferFtpToAzure
{
class Program
{
public static void Main(string[] args)
{
List<FileName> sourceFileList = new List<FileName>();
List<FileName> targetFileList = new List<FileName>();
string targetShareReference = ConfigurationManager.AppSettings["AzureShare"];
string targetDirectoryReference = ConfigurationManager.AppSettings["Environment"] + "/" + Enums.AzureFolders.Mos + "/" + Enums.AzureFolders.In;
string sourceURI = (ConfigurationManager.AppSettings["FtpConnectionString"] + ConfigurationManager.AppSettings["Environment"].ToUpper() +"/"+ Enums.FtpFolders.Mos + "/").Replace("\\","/");
string sourceUser = ConfigurationManager.AppSettings["FtpServerUserName"];
string sourcePass = ConfigurationManager.AppSettings["FtpServerPassword"];
getFileLists(sourceURI, sourceUser, sourcePass, sourceFileList, targetShareReference, targetDirectoryReference, targetFileList);
Console.WriteLine(sourceFileList.Count + " files found!");
CheckLists(sourceFileList, targetFileList);
targetFileList.Sort();
Console.WriteLine(sourceFileList.Count + " unique files on sourceURI" + Environment.NewLine + "Attempting to move them.");
foreach (var file in sourceFileList)
{
try
{
CopyFile(file.fName, sourceURI, sourceUser, sourcePass, targetShareReference, targetDirectoryReference);
}
catch
{
Console.WriteLine("There was move error with : " + file.fName);
}
}
}
public class FileName : IComparable<FileName>
{
public string fName { get; set; }
public int CompareTo(FileName other)
{
return fName.CompareTo(other.fName);
}
}
public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
{
for (int i = 0; i < sourceFileList.Count; i++)
{
if (targetFileList.BinarySearch(sourceFileList[i]) > 0)
{
sourceFileList.RemoveAt(i);
i--;
}
}
}
public static void getFileLists(string sourceURI, string sourceUser, string sourcePass, List<FileName> sourceFileList, string targetShareReference, string targetDirectoryReference, List<FileName> targetFileList)
{
string line = "";
/////////Source FileList
FtpWebRequest sourceRequest;
sourceRequest = (FtpWebRequest)WebRequest.Create(sourceURI);
sourceRequest.Credentials = new NetworkCredential(sourceUser, sourcePass);
sourceRequest.Method = WebRequestMethods.Ftp.ListDirectory;
sourceRequest.UseBinary = true;
sourceRequest.KeepAlive = false;
sourceRequest.Timeout = -1;
sourceRequest.UsePassive = true;
FtpWebResponse sourceRespone = (FtpWebResponse)sourceRequest.GetResponse();
//Creates a list(fileList) of the file names
using (Stream responseStream = sourceRespone.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
line = reader.ReadLine();
while (line != null)
{
var fileName = new FileName
{
fName = line
};
sourceFileList.Add(fileName);
line = reader.ReadLine();
}
}
}
/////////////Target FileList
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
//var test = fileClient.ListShares();
CloudFileShare fileShare = fileClient.GetShareReference(targetShareReference);
if (fileShare.Exists())
{
CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
if (rootDirectory.Exists())
{
CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(targetDirectoryReference);
if (customDirectory.Exists())
{
var fileCollection = customDirectory.ListFilesAndDirectories().OfType<CloudFile>();
foreach (var item in fileCollection)
{
var fileName = new FileName
{
fName = item.Name
};
targetFileList.Add(fileName);
}
}
}
}
}
public static void CopyFile(string fileName, string sourceURI, string sourceUser, string sourcePass, string targetShareReference, string targetDirectoryReference)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceURI + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(sourceUser, sourcePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Upload(fileName, ToByteArray(responseStream), targetShareReference, targetDirectoryReference);
responseStream.Close();
}
catch
{
Console.WriteLine("There was an error with :" + fileName);
}
}
public static Byte[] ToByteArray(Stream stream)
{
MemoryStream ms = new MemoryStream();
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
ms.Write(chunk, 0, bytesRead);
}
return ms.ToArray();
}
public static bool Upload(string FileName, byte[] Image, string targetShareReference, string targetDirectoryReference)
{
try
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
//var test = fileClient.ListShares();
CloudFileShare fileShare = fileClient.GetShareReference(targetShareReference);
if (fileShare.Exists())
{
CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
if (rootDirectory.Exists())
{
CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(targetDirectoryReference);
if (customDirectory.Exists())
{
var cloudFile = customDirectory.GetFileReference(FileName);
using (var stream = new MemoryStream(Image, writable: false))
{
cloudFile.UploadFromStream(stream);
}
}
}
}
return true;
}
catch
{
return false;
}
}
}
}
If I understand you correctly, you want to avoid storing the file in memory between the download and upload.
For that see:
Azure function to copy files from FTP to blob storage.
Using Azure Storage File Share this is the only way it worked for me without loading the entire ZIP into Memory. I tested with a 3GB ZIP File (with thousands of files or with a big file inside) and Memory/CPU was low and stable. I hope it helps!
var zipFiles = _directory.ListFilesAndDirectories()
.OfType<CloudFile>()
.Where(x => x.Name.ToLower().Contains(".zip"))
.ToList();
foreach (var zipFile in zipFiles)
{
using (var zipArchive = new ZipArchive(zipFile.OpenRead()))
{
foreach (var entry in zipArchive.Entries)
{
if (entry.Length > 0)
{
CloudFile extractedFile = _directory.GetFileReference(entry.Name);
using (var entryStream = entry.Open())
{
byte[] buffer = new byte[16 * 1024];
using (var ms = extractedFile.OpenWrite(entry.Length))
{
int read;
while ((read = entryStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
}
}
}
}
}
I want to read Excel file from JSON data which I am sending from ARC, Can anyone help me to sorted out?
public bool ControlAttachment(AttachmentFile file)
{
try
{
if (file != null && file.File != null)
{
string xlsfile = file.File;
string [] xls = {"application/excel","application/vnd.msexcel","xls","xlsx","application/vnd.ms-excel",};
if (xls.ToList().Contains(file.FileType.Trim()))
{
file.FileType = ".xls";
byte[] contents = Convert.FromBase64String(xlsfile);
string LogFilePaths = ConfigurationManager.AppSettings["ExcelMapperPath"];
string fileName = file.FileName.Split('.')[0] + file.FileType;
string LogFile = HttpContext.Current.Server.MapPath(LogFilePaths + file.FileName.Split('.')[0] + file.FileType);
System.IO.File.WriteAllBytes(LogFile, contents);
if (!File.Exists(LogFile))
{
File.Create(LogFile).Dispose();
}
MemoryStream ms = new MemoryStream();
using (var fs = new FileStream(LogFile, FileMode.Open, FileAccess.Write))
{
ms.CopyTo(fs);
ms.Dispose();
}
}
}
return true;
}
catch
{
return false;
}
}