Converting a local folder structure to a folder structure on a server - c#

I'm currently playing around with Paths in .Net and have run into some difficultly with regards to replicating a local folder structure passed as a string from a web service to my site running under localhost on IIS Express.
Essentially, our users will select an image within our desktop software, the local path of which will be sent as a property of the image in our web service. So, when my script accesses the web service, it is fed a string such as:
C:\\Users\\axumadmin\\Pictures\\axumImages\\Countries\\Canada\\canadianFlag.jpg
What our users will then do is FTP this folder structure to a specified directory on our server:
ServerRoot\\umbraco\\axumImages\\Countries\\Canada\\canadianFlag.jpg
The main issue I have here is that I cannot seem to modify the path retreived from the web service to only return the directories from axumImages downwards. So in essence, my local path would be converted to:
axumImages\\Countries\\Canada\\canadianFlag.jpg
I have already tried playing with System.IO.Path to convert this path into the format that I wish to be returned but ultimately all I have acheived so far is either retreiving just the image filename:
canadianFlag.jpg
System.IO.Path.GetFileName(image.FileName);
or the parent directory of the image
C:\\Users\\axumadmin\\Pictures\\axumImages\\Countries\\Canada
Therefore my question is, how can I parse the string so that it is only using axumImages and its descendants?
Any help would be greatly appreciated.

use string.Substring
var startIndex = image.FileName.IndexOf("axumImages");
string test = image.FileName.Substring(startIndex, image.FileName.Length-startIndex)

I ended up solving this in the end using string parsing.
string test = image.FileName.Split(new[] { "axumImages" }, StringSplitOptions.None)[1];
In this example, image.Filename is my filename. So if the filename is:
C:\\Users\\axumadmin\\Pictures\\axumImages\\Countries\\Canada\\canadianFlag.jpg
this will return
\\Countries\\Canada\\canadianFlag.jpg
I can then concatenate this into a usable variable below which then amounts to the path I require:
var actualPath = "axumImages" + "test";

Related

c# - Physical path given, virtual path expected in Server.MapPath

I trying to change my directory which in my local c disk, but where errors says in the title. Is there any way aside from using Server.MapPath?. I'm using a ZipOutputStream nuget package.
I want to locate my directory in C: instead inside the project folder.
public FileResult DownloadZipFileSig(string FileId){
var fileName = "FilesDL".zip";
var tempOutPutPath = Server.MapPath(Url.Content("C:/Users/SDILAP2/Desktop/ID_Esig_Files")) + fileName;
using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(tempOutPutPath)))
{
s.SetLevel(9);
byte[] buffer = new byte[4096];
List<string> stringList = FileId.Split(',').ToList();
List<string> tempList = new List<string>();
foreach (string str in stringList)
{
if (System.IO.File.Exists(Server.MapPath("C:/Users/SDILAP2/Desktop/ID_Esig_Files/" + str + ".jpeg")))
{
tempList.Add(Server.MapPath("C:/Users/SDILAP2/Desktop/ID_Esig_Files/" + str + ".jpeg"));
}
}
stringList = tempList;
for (int i = 0; i < stringList.Count; i++)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(stringList[i]));
entry.DateTime = DateTime.Now;
entry.IsUnicodeText = true;
s.PutNextEntry(entry);
using (FileStream fs = System.IO.File.OpenRead(stringList[i]))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Flush();
s.Close();
}
return File(finalResult, "application/zip", fileName);
}
You might be not quite grasping how web URL's work, and how server.mappath() is to be used.
Web users:
When you have a web based url, then all html markup in a page, or even user supplied URL's are so called web based.
So, if you have a folder from the root of your web site say called MyUpLoads
Then that is just a folder in the web site path names.
eg:
www.mywebsite/UpLoadFiles/cat.jpg
And if you write html markup, then you can and could provide a URL to the above picute, or say with a html image control, you could set the ImageURL or "source" (src) to that file.
And if you using IIS (and not IIS express), then of course you can add what is called a virutal folder. Say some big server drive on ANOHTER computer on the same network.
So, that virtual folder could be anywhere on your network, and of course AGAIN for web HTML, or web URL's, again you use this format:
www.mysite/MassiveFolder/info.pdf
or maybe
localhost:5403/MyUpLoads/cat.jpg
However, in code behind?
ANY code behind (c# or vb.net) ALWAYS uses plane jane WINDOWS file paths.
These are valid full windows file names.
That means that code behind is 100% free to open/read/use/see/play with ANY file on the computer, and any file even on the computer network.
So when you use
server.mapPath("localhost:5403/MyUpLoads/cat.jpg")
Then the above is translated into a local plane jane DOS/WINDOWS file path!!!!
The above may well become
C:\Users\AlbertKallal\source\repos\CSharpWebApp\MyUpLoads\cat.jpg
So keep in mind:
web urls - HTML/asp markup in a page = web based syntax/path.
computer path: plane jane full path names like all windows software.
So, in your case?
var fileName = "FilesDL".zip";
var tempOutPutPath = #"C:/Users/SDILAP2/Desktop/ID_Esig_Files")) + fileName;
So you don't need nor want to user server.mappath, since that is ONLY for a given HTML or web based URL that you want to translate into the local computer file path system.
Since your path name(s) are already in that format, then no need is required.
in fact, keep in mind that you can use this fact to your advantage.
ANY folder (or a vitural folder) will appear in your valid URL's and path names (web based).
However, you might have some pdf's, or sensitive documents. So move that folder OUT of the root or web project folders.
Now, no valid URL's exist, or are even allowed.
However, code behind? It can run, see and use ANY file on your computer - and you use code behind to get those files - but the web site, web side of things has NO ability to use or see or get those files. And you can still do things like say provide a download button, but your code behind can fetch the file, read it and pump it out to the end user (stream the file).
So you only need (have) to use the Server.MapPath function WHEN the URL comes from the web site or html markup. This will translate that web based URL into a regular good old fashion full qualified windows file path name.
However, if you already have that full windows path name, then no URL translate to windows file path is required.
So, for the most part, your code behind can look at, see, grab and play with files on the server. Web users, or web based urls MUST be part of the folders in the web site, but no such restrictions exist for the code behind.
Now, when the code is deployed to a web server, often some file security rights on in place, but as a general rule, that web code behind is NOT limited nor restricted to JUST folders in the web site. Those valued URL's are a restriction for the users and web browsers, and as noted, often a folder outside of the web site is used for security purposes, since no possible valid web based paths can use/see or even resolve to file outside of the root starting folder of the web site.
So for those existing files, you don't need server.mappath.

Storing MSSQL LocalDB for Application

I have been using a LocalDB.mdf file to build my application, but now need to use it in production and create an installable application.
After research, it seems the best place to store such a file is in the /Appdata/Local/ folder.
I intend to create a new LocalDB.mdf file in there if it doesnt already exist, or has been deleted.
I have a pre-made LocalDB.mdf file in my App Resources, which I wanted to copy into this /Appdata/Local/ folder on first run, but I am seeing an Access is denied error.
I can create a blank file ok to that folder.
Here is the code:
string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dvAppDataFolder = appDataFolder + #"\MyApp";
AppDomain.CurrentDomain.SetData("DataDirectory", dvAppDataFolder);
if (!Directory.Exists(dvAppDataFolder))
Directory.CreateDirectory(dvAppDataFolder);
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
{
File.WriteAllBytes(dvAppDataFolder, LokiServer.Properties.Resources.newDB);
}
In addition, Am I going about this the right way?
This line
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
is probably wrong. Missing the backslash, better to use Path.Combine instead of a string concatenation.
Finally, you want to write to a file not to a folder
string fileName = Path.Combine(dvAppDataFolder,"LocalDB.mdf");
if (!File.Exists(fileName))
{
File.WriteAllBytes(fileName, LokiServer.Properties.Resources.newDB);
}
Are you doing it right? It depends. If your app data should be kept separated for each user of your target machine then you are right, but if you want your database to be available to all users of that machine then use
string appDataFolder = Environment.GetFolderPath
(Environment.SpecialFolder.CommonApplicationData);

Convert an array of image physical paths on server to array of urls

I'm using Web Api to return a list of URLs to a client application. Since the Image files get created on the server, when a request comes in I need to respond with a list of the Image path URLs. Right now, I'm using the code below to accomplish this but it's returning physical paths rather than URLs.
string[] imagePaths = Directory.GetFiles(outputImgPath,"*.png");
response.Images = new List<string>(imagePaths);
How could I go about returning the actual urls of the image on the server? I figure I could loop through all the files in the directory and convert them but I'm not sure how to go about that in a performant way.
You can retrieve all file name from directory and add them with web URL
string[] imagePaths = Directory.GetFiles(outputImgPath,"*.png");
imagePaths.Select(x => string.Format("http://DOMAIN/Path/{0}" , Path.GetFileName(x)))

Multiple upload files from file list in User computer to server in ASP.Net

pe someone can help me on this.
I've been googling & searching a lot regarding this issue.
I'm working on web application where I need to :
Click a button to get a folder/directory of files - Done with
javascript
Get list of available files is the selected folder/directory - Done
with javascript
Start uploading those file in the list into server folder - Failed!
As I understand my limitation so far :
I cannot programmatically assign a value to asp:FileUpload control -
readOnly
I cannot access those file in the list in FileInfo/FileStream - it's fail as it can't find the source file given from the list due to it's not
came from server directory
came from server directory
I cannot simply try to use File.Copy to upload the file - it's fail as it can't find the source file given from the list due to it's not
came from server directory
I've been getting error :
"Could not find a part of the path"
List of files in the folder, example :
File1.pdf
File2.png
File3.txt
File4.xls
File5.jpg
While in the server, I already create a folder named as "Temp" but the problem actually because system can't recognize the path of those file in the list.
This is part of my code :
string strPath = #"C:\Users\Administrator\Desktop\Sample";
string strListedFiles = txtList.InnerText.ToString();
string[] strFiles = strListedFiles.split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string strFile in strFiles)
{
FileInfo fiFile = new FileInfo(strPath.ToString() + "\\" + strFile.Trim());
FileStream fsFile = fiFile.OpenRead(); //Failed at here
...
...
...
...
}
Perhaps you are looking for something which has been shown with demo in this tutorial.
This will allow you to upload multiple files concurrently.
Another alternative example with jQuery MultiFile is given here.

ASP.NET MVC Get file from virtual path

For various reasons, in development I occasionally want to intercept a request for, say, ~/MyStyle.css
What I want to do is make the following snippet work:
string absFile = VirtualPathUtility.ToAbsolute(file);
return System.IO.File.ReadAllText(absFile);
This absolute path is absolute for the webserver though, it's not going to map to "C:\whatever". Is there an equivalent method to go to the file system? (Or a ReadFromVirtualPath etc.?)
Use Server.MapPath() to get the file system path for a requested application path.
string absFile = Server.MapPath(file);
or
string absFile = HttpContext.Current.Server.MapPath(file);
You can also use the OpenFile method on VirtualPathProvider to get a Stream pointing at your file
var stream = HostingEnvironment.VirtualPathProvider.OpenFile(file);
var text = new StreamReader(stream).ReadToEnd();
Generally this approach is preferable since you can now, at a later point implement a VirtualPathProvider where, lets say all your css files where located in a database.

Categories

Resources