How to set server.mapath for pdf creation? - c#

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>

Related

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 get the file relative path in c# service project?

I have this code:
Stream stream = new StreamReader("~/quartz.xml").BaseStream;
Q1:What is the "~" symbol specify path in C#?
Q2:How to get the "~" directory in C# service project?
Q3:Does it mean the bin exe directory or project name directory?
The quartz.xml file in my Windows service project located in two position:
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\bin\Debug
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler
Sure the path will change everytime!So get the relative path is better.
Just omit it entirely:
Stream stream = new StreamReader("quartz.xml").BaseStream;
The default directory is the .exe's directory.
Per the OP's edit to the question:
Go to View > Solution Explorer. Right-click the file in question, then choose Properties. Change the Copy To Output Directory option to Copy Always. Then use the code above.
if we use(../quartz.xml):
the StreamReader read path is(not the file actual path):
C:\Windows\quartz.xml
if we use(quartz.xml):
the StreamReader read path is(not the file actual path):
C:\Windows\system32\quartz.xml
This is the way to find the file relative path:
string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
string configFilePath = assemblyDirPath + "\\quartz.xml";
Stream stream = new StreamReader(configFilePath).BaseStream;
So the path is(you can specify either of two):
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\bin\Debug\quartz.xml

Write file to project folder on any computer

I'm working on a project for a class. What I have to do is export parsed instructions to a file. Microsoft has this example which explains how to write to a file:
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
I'm fine with that part, but is there a way to write the file to the current project's environment/location? I'd like to do that instead of hard coding a specific path (i.e. "C:\\test.txt").
Yes, just use a relative path. If you use #".\test.txt" ( btw the # just says I'm doing a string literal, it removes the need for the escape character so you could also do ".\\test.txt" and it would write to the same place) it will write the file to the current working directory which in most cases is the folder containing your program.
You can use Assembly.GetExecutingAssembly().Location to get the path of your main assembly (.exe). Do note that if that path is inside a protected folder (for example Program Files) you won't be able to write there unless the user is an administrator - don't rely on this.
Here is sample code:
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");
This question / answer shows how to get the user's profile folder where you'll have write access. Alternatively, you can use the user's My Documents folder to save files - again, you're guaranteed to have access to it. You can get that path by calling
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If you want to get the current folder location of your program use this code :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text
Full code to write the data to the file :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
string fileName = Path.Combine(path, "test.txt");
if (!File.Exists(fileName))
{
// Create the file.
using (FileStream fs = File.Create(fileName))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}

Save Paths, Virtual directories, and static locations

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);

DirectoryNotFound Exception in C#

I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :
Could not find a part of the path
'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}
Could anyone please tell me how should I save a file at my desirable folder with specifying complete path?
When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.
Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.
As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.
You need to make sure the directory exists prior to creating the text file.
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
if (!info.Directory.Exists)
info.Directory.Create();
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}

Categories