I am trying to upload an image file on an online link of a domain i have bought. Link is live. I can upload it in a local directory. but not working for online link. I cant find the correct way to give online path of my online directory to command
string filePath = HttpContext.Server.MapPath("???");
here is the code.
[HttpPost]
public ActionResult UpdateBanners(UpdateBanners banner)
{
zasa_company_slider sliderData = new zasa_company_slider();
if (banner != null && banner.file.ContentLength > 0)
{
string filePath = HttpContext.Server.MapPath("http://ak.eat-ax.com/akpanel/images/" + Path.GetFileName(banner.file.FileName));
banner.file.SaveAs(filePath);
}
return RedirectToAction("Index");
}
Retrieve your images like this
string filePath = Server.MapPath("~/Images/" + Path.GetFileName(index.FileName));
index.SaveAs(filePath);
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
foreach (string var in filePaths)
{
if (Path.GetFileName(var) == index.FileName)
{
sliderData.SLIDER_IMAGE = ("liveServerURL/" + Path.GetFileName(var));
}
}
Related
I can not upload any file today!
I said "today" because it was working yesterday. I did not change anything that might be related to that.
I always get this error:
Could not find a part of the path
It is worth mentioning that every configuration is declared in program file.
My Uploader method:
public string Upload(IFormFile? file, string path, string fileToRemove = "")
{
if (file == null)
return "";
var directoryPath = $"{_webHostEnvironment.WebRootPath}/{path}";
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
var fileName = $"{DateTime.Now.ToFileTime()}-{file.FileName}";
var filePath = $"{directoryPath}/{fileName}";
using var stream = File.Create(filePath);
file.CopyTo(stream);
if (!string.IsNullOrEmpty(fileToRemove) ||
!string.IsNullOrWhiteSpace(fileToRemove))
{
var fileToRemovePath = $"{_webHostEnvironment.WebRootPath}/{fileToRemove}";
if (File.Exists(fileToRemovePath))
File.Delete(fileToRemovePath);
}
return $"{path}/{fileName}";
}
The image uploading is working perfectly in the development server in the windows environment but when I run the code in the Remote Linux server, the files get uploaded but in the root folder and for which the files can not be accessed by the website.
public async Task<IActionResult> Index(IList<IFormFile> files,Type type)
{
Startup.Progress = 0;
foreach (IFormFile source in files)
{
if (isFileImage(source))
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.ToString().Trim('"');
filename = this.EnsureCorrectFilename(filename);
string serverFilePath = this.GetPathAndFilename(filename);
try
{
await source.CopyToAsync(new FileStream(serverFilePath,FileMode.Create));
}
catch (Exception e)
{
}
finally
{
}
}
}
return Content("Success");
}
private string GetPathAndFilename(string filename)
{
string path = Path.Combine(Directory.GetCurrentDirectory(),#"wwwroot\images\materials", filename);
return path;
}
This is the code responsible for uploading an image. In the development windows environment, it works perfectly as the files get saved in the "wwwroot\images\materials" folder.
But when the code is run the Remote Linux serves the files get uploaded but are saved in the root folder with "wwwroot\images\materials*.jpg" name. Even when running the code in development mode in the Remote server this problem occurs.
Since you're using Path.Combine I would suggest passing each part of the path as a parameter. So instead of #"wwwroot\images\materials" as one parameter, you would pass them separately "wwwroot", "images", "materials".
Try this simple. In this you have to inject _hostingEnvironment so you can get ContentRootPath
string folderName = "Upload/Profile/" + user.Id;
string webRootPath = _hostingEnvironment.ContentRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
string extention = file.ContentType.Split("/")[1];
string fileName = user.Id + ".jpg";
string fullPath = Path.Combine(newPath, fileName);
string envpath = folderName + "/" + fileName;
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
I have an Azure App (.Net 4.5) and I have some static files stored on the filesystem that I want to read from, but I get a System.UnauthorizedAccessException like so
string template = string.Empty;
var file = HostingEnvironment.MapPath("~/App_Data/EmailTemplates/" + fileName);
if (!string.IsNullOrEmpty(file))
{
template = File.ReadAllText(file); <-- Unauthorized Access Exception Here
}
return template;
I know the best practice is Azure Storage, but how do I make this work this way?
As File.ReadAllText states about UnauthorizedAccessException, it could be caused by one of the following conditions:
path specified a file that is read-only.
-or-
This operation is not supported on the current platform.
-or-
path specified a directory.
-or-
The caller does not have the required permission.
You could leverage kudu console and use Attrib command to check the attributes for your files or directories. Also, you could try to use TYPE command to display the contents of your file or click the Edit button from the file list table as follows:
Also, I created a new web app and deployed my MVC application for displaying the files under the App_Data folder, it could work as expected, you could refer to it.
UPDATE:
//method for getting files
public List<DownLoadFileInformation> GetFiles()
{
List<DownLoadFileInformation> lstFiles = new List<DownLoadFileInformation>();
DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/App_Data"));
int i = 0;
foreach (var item in dirInfo.GetFiles())
{
lstFiles.Add(new DownLoadFileInformation()
{
FileId = i + 1,
FileName = item.Name,
FilePath = dirInfo.FullName + #"\" + item.Name
});
i = i + 1;
}
return lstFiles;
}
//action for downloading a file
public ActionResult Download(string FileID)
{
int CurrentFileID = Convert.ToInt32(FileID);
var filesCol = obj.GetFiles();
string fullFilePath = (from fls in filesCol
where fls.FileId == CurrentFileID
select fls.FilePath).First();
string contentType = MimeMapping.GetMimeMapping(fullFilePath);
return File(fullFilePath, contentType, new FileInfo(fullFilePath).Name);
}
UPDATE2:
public ActionResult ViewOnline(string FileID)
{
int CurrentFileID = Convert.ToInt32(FileID);
var filesCol = obj.GetFiles();
string fullFilePath = (from fls in filesCol
where fls.FileId == CurrentFileID
select fls.FilePath).First();
string text = System.IO.File.ReadAllText(fullFilePath);
return Content(text);
}
Here is my code
[HttpPost]
public ActionResult Result(FormCollection form)
{
String Date = form["date"].ToString();
String Directory = Date.Replace("-", "");
//Featch file path
String RootPath = Properties.Settings.Default.FilePath.ToString();
String FilePath = System.IO.Path.Combine(RootPath, Directory, "Call.Log.txt");
FilePath = #System.IO.Path.GetFullPath(FilePath).ToString();
if (System.IO.File.Exists(FilePath))
{
string[] lines = System.IO.File.ReadAllLines(FilePath);
foreach(string line in lines)
{
System.Diagnostics.Debug.WriteLine(line);
}
return null;
} else
{
return View("DirNotFound");
}
//return null;
}
I'm receiving date as 2015-07-27 from form. And D:\ from RootPath. As FilePath output I'm getting D:\\20150727\\Call.Log.txt. The file is really exists in the directory but I'm getting false as System.IO.File.Exists(FilePath). I need your suggestion to fix the issue.
What I'm trying to do is to upload a website using FTP in C# (C Sharp). So I need to upload all files and folders within a folder, keeping its structure. I'm using this FTP class: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class for the actual uploading.
I have come to the conclusion that I need to write a recursive method that goes through every sub-directory of the main directory and upload all files and folders in it. This should make an exact copy of my folder to the FTP. Problem is... I have no clue how to write a method like that. I have written recursive methods before but I'm new to the FTP part.
This is what I have so far:
private void recursiveDirectory(string directoryPath)
{
string[] filePaths = null;
string[] subDirectories = null;
filePaths = Directory.GetFiles(directoryPath, "*.*");
subDirectories = Directory.GetDirectories(directoryPath);
if (filePaths != null && subDirectories != null)
{
foreach (string directory in subDirectories)
{
ftpClient.createDirectory(directory);
}
foreach (string file in filePaths)
{
ftpClient.upload(Path.GetDirectoryName(directoryPath), file);
}
}
}
But its far from done and I don't know how to continue. I'm sure more than me needs to know this! Thanks in advance :)
Ohh and... It would be nice if it reported its progress too :) (I'm using a progress bar)
EDIT:
It might have been unclear... How do I upload a directory including all sub-directories and files with FTP?
Problem Solved! :)
Alright so I managed to write the method myslef. If anyone need it feel free to copy:
private void recursiveDirectory(string dirPath, string uploadPath)
{
string[] files = Directory.GetFiles(dirPath, "*.*");
string[] subDirs = Directory.GetDirectories(dirPath);
foreach (string file in files)
{
ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file);
}
foreach (string subDir in subDirs)
{
ftpClient.createDirectory(uploadPath + "/" + Path.GetFileName(subDir));
recursiveDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
}
}
It works very well :)
I wrote an FTP classe and also wrapped it in a WinForms user control. You can see my code in the article An FtpClient Class and WinForm Control.
I wrote a reusable class to upload entire directory to an ftp site on windows server, the program also renames the old version of that folder (i use it to upload my windows service program to the server).
maybe some need this:
class MyFtpClient
{
protected string FtpUser { get; set; }
protected string FtpPass { get; set; }
protected string FtpServerUrl { get; set; }
protected string DirPathToUpload { get; set; }
protected string BaseDirectory { get; set; }
public MyFtpClient(string ftpuser, string ftppass, string ftpserverurl, string dirpathtoupload)
{
this.FtpPass = ftppass;
this.FtpUser = ftpuser;
this.FtpServerUrl = ftpserverurl;
this.DirPathToUpload = dirpathtoupload;
var spllitedpath = dirpathtoupload.Split('\\').ToArray();
// last index must be the "base" directory on the server
this.BaseDirectory = spllitedpath[spllitedpath.Length - 1];
}
public void UploadDirectory()
{
// rename the old folder version (if exist)
RenameDir(BaseDirectory);
// create a parent folder on server
CreateDir(BaseDirectory);
// upload the files in the most external directory of the path
UploadAllFolderFiles(DirPathToUpload, BaseDirectory);
// loop trough all files in subdirectories
foreach (string dirPath in Directory.GetDirectories(DirPathToUpload, "*",
SearchOption.AllDirectories))
{
// create the folder
CreateDir(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
Console.WriteLine(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
UploadAllFolderFiles(dirPath, dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory))
}
}
private void UploadAllFolderFiles(string localpath, string remotepath)
{
string[] files = Directory.GetFiles(localpath);
// get only the filenames and concat to remote path
foreach (string file in files)
{
// full remote path
var fullremotepath = remotepath + "\\" + Path.GetFileName(file);
// local path
var fulllocalpath = Path.GetFullPath(file);
// upload to server
Upload(fulllocalpath, fullremotepath);
}
}
public bool CreateDir(string dirname)
{
try
{
WebRequest request = WebRequest.Create("ftp://" + FtpServerUrl + "/" + dirname);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Proxy = new WebProxy();
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.PathnameCreated)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
public void Upload(string filepath, string targetpath)
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FtpUser, FtpPass);
client.Proxy = null;
var fixedpath = targetpath.Replace(#"\", "/");
client.UploadFile("ftp://" + FtpServerUrl + "/" + fixedpath, WebRequestMethods.Ftp.UploadFile, filepath);
}
}
public bool RenameDir(string dirname)
{
var path = "ftp://" + FtpServerUrl + "/" + dirname;
string serverUri = path;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.Rename;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
// change the name of the old folder the old folder
request.RenameTo = DateTime.Now.ToString("yyyyMMddHHmmss");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.FileActionOK)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
}
Create an instance of that class:
static void Main(string[] args)
{
MyFtpClientftp = new MyFtpClient(ftpuser, ftppass, ftpServerUrl, #"C:\Users\xxxxxxxxxxx");
ftp.UploadDirectory();
Console.WriteLine("DONE");
Console.ReadLine();
}
Unless you're doing this for fun or self-improvement, use a commercial module. I can recommend one from Chilkat, but I'm sure there are others.
Note: I'm pretty sure this does answer the stated problem, What I'm trying to do is to upload a website using FTP in C# (C Sharp).