File.Move on client machine Asp.net MVC - asp.net-mvc

Silly question but here goes...
Is it possible to write an intranet windows auth asp.net mvc app that uses File.Move to rename a file on a users machine? Or will the File.Move and using Path.GetDirectory and other System.IO functions look on the IIS server directory structure instead of the client machine?
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, string append)
{
try
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
DirectoryInfo filepath = new DirectoryInfo(file.FileName);
string parentpath = Path.GetDirectoryName(filepath.FullName);
DirectoryInfo searchablePath = new DirectoryInfo(parentpath);
var directories = searchablePath.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo d in directories)
{
if (!string.IsNullOrEmpty(append) && !d.Name.Contains(append))
{
string fName = Path.GetFileNameWithoutExtension(d.Name);
string fExt = Path.GetExtension(d.Name);
System.IO.File.Move(d.FullName, Path.Combine(d.DirectoryName, fName + append + fExt));
}
}
}
}
catch (Exception ex)
{
}
return View();
}
I have tried this but am getting a filenotfoundexception.
Any ideas?

The ASP.NET code runs on the server, so it will look at the files on the server.
You can't rename a file on the client machine, however it would be possible to rename a file on the computer that is used as client, if:
the server and computer are on the same network
the server knows the name of the computer
the server knows which folder to look for in the computer
the folder is shared with the user account running the ASP.NET code on the server with enough privileges to change the name of a file
In that sense the computer is not a client to the server, but the server communicates directly with the computer via the file system, not via IIS.

These will indeed work only on the server.
You may look at the various file and filesystem related specifications for client-side javascript APIs provided by the user's browser:
http://www.w3.org/TR/FileAPI/
http://www.w3.org/TR/file-system-api/
http://www.w3.org/TR/file-writer-api/

Related

Save file to path desktop for current user

I have a project ASP.NET Core 2.0 MVC running on IIS.
Want to Export some information from data grid to Excel and save it from web page to the desktop of current user.
string fileName = "SN-export-" + DateTime.Now + ".xlsx";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
fileName = rgx.Replace(fileName, ".");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName2 = Path.Combine(path, fileName);
FileInfo excelFile = new FileInfo(fileName2);
excel.SaveAs(excelFile);
This works perfect local at Visual Studio, but not after publishing at IIS.
Using simple path string path = #"C:\WINDOWS\TEMP"; It will save this export file at the server temp folder, but not current web page user.
How to get this?
ASP.NET MVC is framework for a web application. So you have fronted and backend parts. This code will executed on the server side of your application. Even if you use Razor pages, they also generated at the backend. So there are several ways to save data on the computer:
use js to iterate data and save it, but I'm not sure that saving to excel with js is easy;
send desired data to backend, save it to excel and then return to the client.
For a second way you can use next code:
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(YourData data) {
Stream stream = await {{__get_stream_based_on_your_data__}}
if(stream == null)
return NotFound();
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
And because of security reasons you can save data only to downloads directory.

Storing local files with ASP.NET Core and MVC

With Asp.NET Core, The handy path-finding functions in Environment are gone. HttpContext and HttpServerUtility have been stripped. And the Application store within the Cache framework is gone. I can no longer assume (in code) that my server is using IIS or that it's even running on a Windows box.
And I don't have a database; I have a set of JSON files. Which, for reasons outside the scope of this question, cannot be stored in a database.
How do I read and write to files on the server?
In the new ASP.NET Core world when we deploy we have 2 folders appRoot and wwwroot
we generally only put files below the wwwroot folder that we intend to serve directly with http requests. So if your json files are to be served directly ie consumed by client side js then maybe you would put them there, otherwise you would use a different folder below appRoot.
I will show below how to resolve paths for both scenarios, ie sample code how to save a json string to a folder below either appRoot or wwwroot. In both cases think of your location as a virtual path relative to one of those folders, ie /some/folder/path where the first / represents either appRoot or wwwroot
public class MyFileProcessor
{
public MyFileProcessor(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
hostingEnvironment = env;
appEnvironment = appEnv;
appRootFolder = appEnv.ApplicationBasePath;
}
private IHostingEnvironment hostingEnvironment;
private IApplicationEnvironment appEnvironment;
private string appRootFolder;
public void SaveJsonToAppFolder(string appVirtualFolderPath, string fileName string jsonContent)
{
var pathToFile = appRootFolder + appVirtualFolderPath.Replace("/", Path.DirectorySeparatorChar.ToString())
+ fileName;
using (StreamWriter s = File.CreateText(pathToFile))
{
await s.WriteAsync(jsonContent);
}
}
public void SaveJsonToWwwFolder(string virtualFolderPath, string fileName string jsonContent)
{
var pathToFile = hostingEnvironment.MapPath(virtualFolderPath) + fileName;
using (StreamWriter s = File.CreateText(pathToFile))
{
await s.WriteAsync(jsonContent);
}
}
}

facing error while uploading file in mvc5 on server

I have MVC5 application , where I need to upload file excel and then then create data table of this excel. I use devexpress control to upload file. I use following code to store uploded file and then read in datatable and then store in database.
if (e.UploadedFile.IsValid)
{
e.UploadedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/" + e.UploadedFile.FileName));
var Filepath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/" + e.UploadedFile.FileName));
DataTable dtReport = new DataTable();
try
{
dtReport = CreateDataTableFromExcelFile(Filepath, "A1:U", true, "Sheet1").Tables[0];
}
catch
{
}
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
System.Data.SqlClient.SqlBulkCopy sqlcopy = new System.Data.SqlClient.SqlBulkCopy(con);
sqlcopy.DestinationTableName = "table_Name";
sqlcopy.WriteToServer(dtReport);
con.Close();
If I host this application on IIS on my machine then it works fine. But If I host it on another server then it shows error
Access to the path 'C:\inetpub\wwwroot\MVC_Project_v3\App_Data\UploadTemp\dxupload_19aafa62643d42418b2fe5eaadede3cfcugxrc4e.nrt.tmp' is denied.
Please suggest right solution
The credential you are using to host the WebSite (the credential you enter in the application pool identity) does not have the privilege to access that directory.
Add a valid credential here.

PDF JS, from file location

I have successfully set up using the viewer with the following code:
protected void btnShowPDFS_OnClick(object sender, EventArgs e)
{
// Display all files.
string[] files = Directory.GetFiles(#"D:\Reports\2014\July\", "*.PDF");
var pdfNames = new List<string>();
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string queryString = "/web/viewer.html?file=" + System.Web.HttpUtility.UrlEncode("../July/" + fileName);
pdfNames.Add(queryString);
}
listView.DataSource = pdfNames;
listView.DataBind();
}
Now, this all works fine if all my PDF's are in a folder within the website (i.e localhost). However, how do i point the view to either a network share, or just another folder on the same machine, but outside of IIS?
A browser's XMLHttpRequest might have a restrictions for local files access (Firefox has more relaxed policy for local file than other browsers).
PDF.js is using XHR; and PDF.js also allows "load" files from a typed array (Uint8Array). You can use the latter in your solution. Notice the Internet Explorer (WebBrowser control) has window.external that can be used to transmit the data from the host application, see http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting(v=vs.110).aspx

Access to the path denied, trying to access remote server file

I'm having a hard time trying to access a remote server file from other server with my asp .Net application (C#) hosted in it. The scenario is the following:
I wrote an MVC web application that is hosted on SERVER A; and in some instance, it has to let the user modify a XML configuration file that is located on SERVER B. So, here is the part of the code where I try to read that file from a shared folder on SERVER B:
(C# - Controller)
WindowsImpersonationContext impContext = null;
try
{
impContext = NetworkSecurity.ImpersonateUser(
Settings.Default.ImpersonationDomain,
Settings.Default.ImpersonationUser,
Settings.Default.ImpersonationPass,
LogonType.LOGON32_LOGON_NETWORK,
LogonProvider.LOGON32_PROVIDER_DEFAULT);
}
catch (ApplicationException ex)
{
// write to log file
}
if (null != impContext)
{
try
{
//get the location of the configuration file
string remoteConfigFile = Settings.Default.RemoteDesktopMonitorCnfgFile;
//open the configuration file
XDocument xmlFile = XDocument.Load(#"\\SERVERB\Folder\configurationFile.exe.config");
So, my exception is here, when I try to open that configuration file, I'm getting the exception:
Access to the path '\\SERVERB\Folder\configurationFile.exe.config' is denied
As you could see, I'm impersonating the user before I try to read the file, that impersonation is well done; and I already gave full access to the shared resource to the user that I'm impersonating with. I even tryied joining that user to the Administrators group on both Servers (A and B) and the same exception occurs.
Maybe worth to say that both Servers are on the same Windows Domain, and that I'm using a user account that exists on the domain and that the password is correct.
Any help you could give me would be appreciate.
Thanks in advance.
There is a solution to your problem already on StackOverFlow
Check it out!

Resources