Save Paths, Virtual directories, and static locations - c#

I had a file upload that was uploading to a folder in the web application root, i.e. I had
string savePath = #"~/documentation/"
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath(savePath) + filename);
and that worked fine, uploading the file to WebApp/documentation/filename.abc
The problem is, I want to change the documentation location so I don't have to move that folder when pushing from development to production. So I did the following
In Web.Config:
<appSettings>
<add key="DocumentationLocation" value="C:\Documentation\" />
</appSettings>
In the code:
string savePath = ConfigurationSettings.AppSettings["DocumentationLocation"];
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath(savePath) + filename);
I figured this would work identically, saving the file to the folder specified in the web.config.
However, I get an error when I try to upload a document now, that says:
'C:\TM_Documentation\' is not a valid virtual path.
any idea what i'm doing wrong so that i can fix it and save the files outside of the web app directory? Thanks.

Remove the Server.MapPath(), you don't need the server to map the path for you, because you are giving a full path already.

You don't need a Server.MapPath if you have your path as "C:\Documentation\".
Server.MapPath is required only if you config has a relative path such as "~/Documentation/"
Try this
FileUploadControl.SaveAs(savePath + filename);

Related

How to get static file directory

In my solution, I have static file directory at project ApiCon and my code is need to get static file directory is in project BLL and the file path url is /image/myimg.png.
Now that file can show in front end completely. I need to delete my image in static file directory when I call Api in controller, But I can't get path to delete that file.
How to get static file directory?
if (File.Exists(path))
{
File.Delete(path);
}
P.S. I need not to use Directory.GetParent() for find directory in other project.
Static files, while they should be located in the application folder, can be placed in whatever folder you want.
They could be in:
application_root/files/
application_root/files/static/
application_root/superman/batman/robinhood/
On the plus side, you get to put them wherever you want, even in multiple location. On the down side, there is no default static file directory.
Which means you'll have to keep track of the directory itself. The best way to store such information is in the web.config file of your application.
1. Add the config key in the <appSettings> of your web.config file.
<add key="StaticFileDirectory" value="MyStaticFiles" />
2. Add a reference to System.Configuration in your project.
It's listed under Assemblies > Framework.
3. Retrieve the config value.
string foldername = ConfigurationManager.AppSettings["StaticFileDirectory"];
4. Convert it to an absolute path.
string absoluteFolderPath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, foldername);
5. Use it as you want to.
string absoluteFilePath = System.IO.Path.Combine(absoluteFolderPath, filename);
if (File.Exists(absoluteFilePath))
{
File.Delete(absoluteFilePath);
}
You can solve this issue by this way.
This function will search all subdirectories inside the given folder path ex:"C:\Users\NBY81HC\Desktop\hello" to return the file you want.
foreach (string file_path in Directory.GetFiles(#"C:\Users\NBY81HC\Desktop\hello", "test.txt", SearchOption.AllDirectories))
{
Console.WriteLine(file_path);//Return C:\Users\NBY81HC\Desktop\hello\aa\a2\test.txt
File.Delete(file_path);
}

Get the filepath of a static file to work local and on server

I want to provide a new file needed for configuring my application - here it's the settings.json:
How do I get the correct path of the file?
I tried:
System.Reflection.Assembly.GetExecutingAssembly().Location // gets a DLL somewhere /Temporary ASP.NET Files/
but when I publish it to a customers server the location is next to the web.config like this (and is a different path):
Any idea?
You can use AppDomain.CurrentDomain.BaseDirectory to get base directory of your application.
Something like this should work:
string settingsJson = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");
You can try one of these two methods:
string path = System.IO.Directory.GetCurrentDirectory();
string path = Environment.CurrentDirectory;
Path.Combine(path, "settings.json");

How can i replace path with file name?

Hello i have to finish school project after another student.
And in whole program he used absolute path to file, the problem is it only works at one computer. Cuz this path is unique.
Could anybody tell me how can i replace this path just with file name?
string content = File.ReadAllText(filePath);
this.DocumentXml = XDocument.Parse(content);
this.xmlInfo = XDocument.Parse(content);
var groups = this.DocumentXml.Root.Elements("group");
foreach (var group in groups)
{
checkedListBox1.Items.Add(group.Attribute("name").Value);
}
// Adding data from your DNSFile to dataGridView1
hostsDataSet.Clear();
hostsDataSet.ReadXml(filePath);
dataGridView1.DataSource = hostsDataSet;
dataGridView1.DataMember = "item";
In this case "filepath" is text file with absolute path with file that he used.
Can you help me?
This is whole path to the file, that i create with Application.LocalUserAppDataPath: C:\Users\praktykant1\AppData\Local\WindowsFormsApplication1\WindowsFormsApplication1\1.0.0.0\test.txt
Problem in my case is that i have to create file that i use in program in AppData/Local folder.So on every computer the path will be different. And this program must work on every computer. Im just beginner so i am green in this subject.
This is precisely what config files are for... differences between environments in which the same code might execute.
Presumably the problem is that filePath is hard-coded, yes? Something like this?:
var filePath = #"c:\some\path\to\a\file.xml";
Instead, make that a configuration value. First add an entry to the App.config (or Web.config if this is a web application) in the appSettings node:
<appSettings>
<add key="filePath" value="c:\some\path\to\a\file.xml" />
<!-- any other settings already in place... -->
</appSettings>
Then use ConfigurationManager to get that setting. (You may need to add a reference to the System.Configuration assembly in the project.) Something like this:
var filePath = ConfigurationManager.AppSettings["filePath"];
You might also perform some error checking to make sure there's a value there at all (make sure filePath doesn't end up as a null or empty string, that is), make sure the file exists, etc.
At this point you can change the value in the config file without having to re-compile the code. So any new environment can set the config setting and use the application.
To get the file name of a path, just do this.
For example if your path is "C:\hello.txt", it becomes "hello.txt"
string fileName = Path.GetFileName(filepath);
If you do not like your file name to have any extensions
string fileNameNoEx = Path.GetFileNameWithoutExtension(fileName);
That way it becomes "hello"
If you set the variable filepath to be just the filename - it would look for this file in the directory where the executable file was started from (by default). This is called the working directory and you can find how to change the working directory online.
If you want to avoid using a full (or relative) path and just use the filename - expect it to be in that working directory.
In case of ASP.net you can do this,
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}

How to set server.mapath for pdf creation?

I am generting pdf documents using itextsharp. I have set a string path. program works properly but the pdf file saves in my project folder. I want to set this path to my system F disk. My current code is
string path = Server.MapPath("Reports");
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path +""+name+".pdf", FileMode.Create));
System.Diagnostics.Process.Start(path + "name.pdf");
How can I Set string path = Server.MapPath("Reports"); to my system F disk. I applied strait path like
string path = Server.MapPath(#"F:\reports\");
but it shows error like its not a virtual path..How can I do this??
All MapPath does is turn a relative path in your IIS project to the absolute path the IIS project is deployed to. If you want to use the fixed path just enter a fixed path
string path = #"F:\reports\";
You could also add it to the application settings in your web.config and read the path from there.
//In your code
var path = WebConfigurationManager.AppSettings["savePath"];
<!-- in web.config -->
<appSettings>
<add key="savePath" value="F:\reports\"/>
</appSettings>

Saving an uploaded file with HttpPostedFileBase.SaveAs in a physical path

I'd like to save an uploaded file to a physical path by the method HttpPostedFileBase.SaveAs().
When I choose a physical path, an exception appears indicates that the path must be virtual.
var fileName = Path.GetFileName(fileurl.FileName);
var path = "C:/Projets" + fileName;
fileurl.SaveAs(Server.MapPath(path));
How can I change my code to be able to save the file every where I want?
The Server.MapPath works only with physical locations that are part of the website. If you want to save the file outside you could use the following:
var fileName = Path.GetFileName(fileurl.FileName);
fileurl.SaveAs(Path.Combine(#"c:\projects", fileName));
Make sure though that the account under which your application pool is executing is granted write permissions to this folder.
Server.MapPath is for virtual path. You can try to use Path.GetFullPath(path).

Categories