I'm using a web browser and the uri that the web browser displays is constantly changing.
The exact location of the uri is not known as users will install the program containing the files to their Program Files folder.
If I use
directoryString += Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
It will return C://Program Files (x86) as I want it to but how do I merge this into a uri?
So I basically want
this.webBrowser1.Url = new Uri("file://" + directoryString + "myFolder/StoryBox/desert.html");
So if it ran it would be file://C:/Program Files (x86)/myFolder/StoryBox/desert.html);
P.S. I need it with the string incase the OS is 32 bit and it wont have the Program Files (x86) folder and I'm not writing C:/ incase they have a different drive name.
You almost have the answer in your question. Let me know if I'm missing something.
var folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
var path = Path.Combine(folder, "myFolder/StoryBox/desert.html");
var uri = new Uri("file:" + path);
Related
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.
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);
The program I am writing is a stock inventory system.
So the PC I wrote the program on can locate the files and folders to update on the PC as necessary as the path is valid.
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts"))
{
Directory.CreateDirectory(path);
}
var fileName = #"c:\Users\ThisPC\Documents\Stock Documents\Tyre_File.xml";
This line is also used when I am updating quantities when an order is taken.
So obviously when I run this program in visual studio on another PC this path isn't recognized.
Is there a way that I can add a pointer to create and store my folder and documents in the My Documents on any pc the program loads in?
UPDATE-------------------------------------------------------
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts"))
{
Directory.CreateDirectory(path);
}
This is the only one it wont work for, it creates a folder within a folder when the form is loaded, but your method doesnt work for that?
I believe that
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
is what you are looking for
You want the environment variable for MyDocuments, which will be unique for each user/computer.
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
So I have a small setup file that needs to install a few run-time files. The files are located within sub directories of the root of the drive. The drive letter will be different on every customers machine, so I was trying this and several other methods to no avail.
// File is being ran from D:\ "eg: D:\setup.exe"
// All my runtimes are in the Tools\Runtime direcorties
string path = Directory.GetCurrentDirectory();
string ext = "/q /norestart";
string location = "\\Tools\\Runtimes\\Net\\";
string step1 = "dotnetfx35.exe";
var process = Process.Start(path + location + step1 + ext);
process.WaitForExit();
As you pros and more experienced programmers know, for some reason... It doesn't work
I keep getting file not found.
I'm developing a C# asp.net web application. I'm basically done with it, but I have this little problem. I want to save xml files to the "Users" folder within my project, but if I don't psychically hard code the path "C:......\Users" in my project it wants to save the file in this "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\Users" folder, this is an annoying problem because I can't use the hard coded directory on our web hosts server. Also, I have a checkbox list that populates from the the "DownloadLibrary" folder in my project, and its suppose to download the files from that fold but its also looking to the "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" folder for download even though its populating from the correct folder. I'm very confused by this, its the first time something like this has ever happened to me. Can anyone please help me with this, its the only thing standing in my way to complete this project.
You don't want to use the working directory at all; you want to use a directory relative to where the web application is located (which can be retrieved from HttpRequest.ApplicationPath.
HttpRequest request = HttpContext.Current.Request;
// get the physical path to the web application
string pathToApp = request.MapPath(request.ApplicationPath);
string usersPath = System.IO.Path.Combine(pathToApp, "Users");
Update
As VincayC points out; asp.net development is not my strongest skill ;) The above code is essentially equivalent of this (much simpler) code:
string usersPath = HttpRequest.Current.Request.MapPath("~/Users");
If this code appears in the code-behind of a page, you can probably cut HttpContext.Current as well, since the page has a Request property.
That did fix the one problem I'm having, but the downloads are still not downloading from the right place, the program still wants to get the files from "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" directory here is the code I'm using
--Code to populate the checkbox--
HttpRequest request = HttpContext.Current.Request;
// get the physical path to the web application
string appPath = request.MapPath(request.ApplicationPath);
string directory = System.IO.Path.Combine(appPath, "DownloadLibrary/");
// Get the list of files into the CheckBoxList
var dirInfo = new DirectoryInfo(directory);
cblFiles.DataSource = dirInfo.GetFiles();
cblFiles.DataBind();
--Download Button Code--
// Tell the browser we're sending a ZIP file!
var downloadFileName = string.Format("Items-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
// Zip the contents of the selected files
using (var zip = new ZipFile())
{
// Add the password protection, if specified
/*if (!string.IsNullOrEmpty(txtZIPPassword.Text))
{
zip.Password = txtZIPPassword.Text;
// 'This encryption is weak! Please see http://cheeso.members.winisp.net/DotNetZipHelp/html/24077057-63cb-ac7e-6be5-697fe9ce37d6.htm for more details
zip.Encryption = EncryptionAlgorithm.WinZipAes128;
}*/
// Construct the contents of the README.txt file that will be included in this ZIP
var readMeMessage = string.Format("Your ZIP file {0} contains the following files:{1}{1}", downloadFileName, Environment.NewLine);
// Add the checked files to the ZIP
foreach (ListItem li in cblFiles.Items)
if (li.Selected)
{
// Record the file that was included in readMeMessage
readMeMessage += string.Concat("\t* ", li.Text, Environment.NewLine);
// Now add the file to the ZIP (use a value of "" as the second parameter to put the files in the "root" folder)
zip.AddFile(li.Value, "Your Files");
}
// Add the README.txt file to the ZIP
//zip.AddEntry("README.txt", readMeMessage, Encoding.ASCII);
// Send the contents of the ZIP back to the output stream
zip.Save(Response.OutputStream);</pre></code>
I'm not sure how to get the downloads to point to my application directory,I tried everything I can think off.