Writing file to web server - ASP.NET - c#

I simply want to write the contents of a TextBox control to a file in the root of the web server directory... how do I specify it?
Bear in mind, I'm testing this locally... it keeps writing the file to my program files\visual studio\Common\IDE directory rather than my project directory (which is where I assume root is when the web server fires off).
Does my problem have something to do with specifying the right location in my web.config? I tried that and still no go...
Thanks much...
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
StreamWriter _testData = new StreamWriter("data.txt", true);
_testData.WriteLine(TextBox1.Text); // Write the file.
_testData.Close(); // Close the instance of StreamWriter.
_testData.Dispose(); // Dispose from memory.
}

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine(TextBox1.Text); // Write the file.
}
}
Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.

There are methods like WriteAllText in the File class for common operations on files.
Use the MapPath method to get the physical path for a file in your web application.
File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
w.WriteLine(TextBox1.Text); // Write the text
}
}

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.
Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

Related

Handle files from OnFileActivated()

I have problem with handling files passed to my application in OnFileActivated(). First, I've registred specific file extention in Package.appminifest of my application, so after tap into specific file my application starts and run OnFileActivated function.
In my case file is archive zipped with System.IO.Compression.ZipArchive, but I think it's not crutial here. Beggining of my function looks as follow:
protected override async void OnFileActivated(FileActivatedEventArgs args) {
base.OnFileActivated(args);
var file = args.Files[0];
using (var archive = ZipFile.OpenRead(file.Path)) {
...
As some of you can expect I get an error when I'm trying to access file in last line. I also tried different solutions as copying file into local folder and then access it, but also without luck.
Question
Is there any way to do such thing? Or maybe I'm doing it completely wrong way?
Using the Path property will not be useful for a brokered file (such as you get from Activation). Use the constructor that takes a Stream instead.
Here is the correct answer:
protected override async void OnFileActivated(FileActivatedEventArgs args) {
base.OnFileActivated(args);
var file = (StorageFile)args.Files[0];
using (var archive = new ZipArchive(await file.OpenStreamForReadAsync())) {
...
I haven't noticed before that ZipArchive have constructor which takes stream as a parameter.

C#: Writing a RTF (Text) file to system drive

I have a program which contains a richTextBox and a Button. Upon clicking the button, the program gets the text from richTextBox and saves it to a predefined location stored in a string variable.
If I change this location to C drive which is my System Drive, it won't allow me to do it and throws a System.UnauthorizedAccessException.
I am also the admininstrator of my PC. Is there any way that I can get permissions or work something out to solve this issue? Thanks in advance.
I use the following code
private void button1_Click(object sender, EventArgs e)
{
string temp = location;
System.IO.StreamWriter file = new System.IO.StreamWriter(temp);
file.WriteLine(this.richTextBox1.Rtf);
file.Close();
}
Trying to write files directly to the root of the c: drive often cause problems, such as the exception you're seeing.
Try storing your file somewhere else. A good way of getting a safe folder is to use the SpecialFolder enumeration: (change it to Desktop, MyDocuments, or whatever might be appropriate in your case)
string temp
= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myFile.txt")
System.IO.StreamWriter file = new System.IO.StreamWriter(temp);
Considering your update, try this instead:
string temp
= Path.Combine(#"C:\Users\MuhammadWaqas\SkyDrive", "myFile.txt");
As pcnThird suggested, you could save it to "myFile.rtf" instead and take advantage of the file type, assuming you're going to be opening the file and reading the contents outside of your app.
You have to specify a file name instead of a folder, try changing location to "C:\Users\MuhammadWaqas\SkyDrive\test.txt"
Check your location. You might be trying to write to a non existent or restricted location

Reading a file added manually in project as resource in VisualStudio

In my soloution, for one of the projects I have to add a binary file and read its content in the form_load event.
As you can see in the picture I have added it to the appropriate project and have set the Build Action to Content and Copy to Output Directory as Copy Always.
Now can somone please tell me how how to access this file?
private void SetupForm_Load(object sender, EventArgs e)
{
//Find the path to file then
//READ THE FILE
}
Now you should find this file in your output directory after building your project. Given the right path to the file, you can access this file with any method you want.
Some methods can help you to get the path to the file:
Directory.GetCurrentDirectory();
Environment.CurrentDirectory
I'm not sure exactly what you're trying to do with the file, and that will determine your best approach here. As per the answer here you have a couple of options. To paraphrase:
Serialization
Binary Reader
I think the best method was this, so far:
So when I add the file to the project, it will be in the same folder as the exetubale file of project resides. So for getting the path (including the name of exetuable file I had to use Application.ExecutablePath and to remove the file name and have the pure path to the folder I had to use Path.GetDirectoryName() and finally add the filename I wanted to acces to this path, as you can see below:
var path = Path.GetDirectoryName(Application.ExecutablePath) + "\\YourFileName.bin";
The API you call to read the file depends upon the type of file. But the general pattern is like this.
private void SetupForm_Load(object sender, EventArgs e)
{
System.IO.Stream input = Application.GetResourceStream(new Uri #"/MyApp;component/content.bin", UriKind.Relative)).Stream;
BinaryReader binaryReader = new BinaryReader(input);
}
You can directly readbytes from the file attached as resource.My resource in this example is SampleWordnew document.
byte[] bob = ReadBytesfromResources.Properties.Resources.SampleWordnew ;

Locating a file directory to display pdf in c#

I am having a problem with displaying a pdf in my form wen a menu item is clicked
the directory im using cant be found
the file is in the project folder
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"\\ColsTechieApp\\TechnicianApplicationUserManual.pdf");
}
when i enter the full location
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"C:\Users\UV Chetty\Dropbox\Final\Complete\ColsTechieApp (Complete)\ColsTechieApp\Technician Application User Manual.pdf");
}
it works how do i make the path exclusive to the project folder
Try using Environment.CurrentDirectory as your current set and combin it with Path.Combine
Should work, becaus you are using full path
First, you're trying to escape backslashes but the # specifies that the string shouldn't be escaped. (Plus, you seem to be missing whitespaces)
Secondly, Environment.CurrentDirectory inserts the current path. Used with Path.Combine, you'll have your entire location.
If you're really lazy, you can skip the Path.Combine and directly concatenate strings. Process.Start() probably converts it to a Path automatically.

How to embed CHM file in application

Hey everyone,
I just finished up an application I've been working on for a while now. Probably the most complex one I've made to date. Due to this, I figured I'd go and make a help document to provide users with some info on it.
I've created a CHM file, and set up a helpProvider, however now my problem is how to include this and the HHC (Table of contents) file with my application. I feel like it'd be a pain to require the user to copy the two files themselves, so I'm trying to store them as embedded resources, then have the application write these out in the current directory.
Currently, this is the code I'm using:
var data = Properties.Resources.RERHelp;
using (var stream = new FileStream("RERHelp", FileMode.Create))
{
stream.Write(data, 0, data.Count() - 1);
stream.Flush();
}
helpProvider1.HelpNamespace = Directory.GetCurrentDirectory() + "\\RERHelp\\RERHelp.chm";
This works just fine, but it means I'd have to run through this twice, once with data set to Properties.Resources.RERHelp, and once for the Table of Contents file. Is there a better way to do this? Perhaps some way to embed the CHM and HHC files in the application, and access them without writing them to disk? If that isn't possible, which I'm thinking it isn't, is there a better way to go about it than how I am currently?
Thanks for any help!
Best Regards,
Ian
Apps usually use an installer, or zip archive of some sort. Both methods would allow a user to receive the application and the help files, without having to provide them separately.
Under your project properties - Resources, add a file resource ie:textmag.chm. I use filetype Text for the chm's
private void HelpToolStripMenuItem_Click(object sender, EventArgs e)
{
string helpFileName = "";
try
{
helpFileName = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources") + #"\TextMag.chm";
Help.ShowHelp(this, helpFileName);
}
catch (Exception ex)
{
string xxx = ex.Message;
}
}
Important: in the properties of the chm file under resources, the Build Action must be Content.
Oh, wow. Turns out I didn't need the HHC file as well. I assumed I did because when I'd open the help dialog, it would say that it couldn't find the table of contents.hhc file. I assumed for some reason it needed that in addition to the CHM. I originally just made a method to pass the resources to so as to prevent redundancy, and called that once for the CHM, and once for the HHC, but then I noticed this bit:
data.Count() - 1
I'm not sure why that - 1 was there, the solution I found had it, so I just left it there. When I removed that, the program ran, wrote out that file, and could then read it for the help documentation without the complaint of the missing HHC. All is well. Thanks for the suggestions, everyone!
So a solution is:
1) Copy your chm file to the required project folder
2) In your Visual C# solution explorer add existing item to the project (your chm file).
3) Select the Project menu then project properties.
4) Add existing resource.
5) Add the below code and connect to your help menu item.
private void WORKING_HELP()
{
string filePath = Directory.GetCurrentDirectory() + "\\BlitzHelp.chm";
try
{
//Check if already exists before making
if (!File.Exists(filePath))
{
var data = Properties.Resources.BlitzHelp;
using (var stream = new FileStream("BlitzHelp.chm", FileMode.Create))
{
stream.Write(data, 0, data.Count());
stream.Flush();
}
MessageBox.Show("file made");
}
}
catch
{
//May already be opened
}
Help.ShowHelp(this, filePath);
}

Categories