with openFileDialog you would select a file and after pressing "OPEN" it would paste the filepath of the selected file (c:\blob\template) into an textbox.
I would like to do automatically select the file c:\blob\template en then put the filepath in the textbox. basically the exact same thing as openfiledialog without a dialog. i have been trying to do this for some time now. can somebody help me out with this? i have no clue how to realise this.
i`m only able to get the filepath and paste the string in the textbox but this but only fills the box with a string. i need to load the file/template in there.
private void txt()
{
string fileName = "template";
string fullPath;
fullPath = Path.GetFullPath(fileName);
lblFirstTemplate.Text = fullPath;
}
Thank you in advance!
The code you now have will only get the file path. What you need to add is code that will actually open the file and read its content.
Let's say your file contains some text. You can use the following line to read the complete file as text:
System.IO.File.ReadAllText(fullPath);
If your file contains some other data like binary data, you can use:
System.IO.File.ReadAllBytes(fullPath);
And instead of reading all data at once, you can read it one line or a couple of bytes at a time. A good place in the documentation to start is: Common I/O Tasks
Related
I'm attempting to do two things. I want to embed a text file into my project so that I can utilise it and modify it, but at the same time I don't want to have to package it when I send the project out to users (I.E included in the exe file).
I've had a look around and there's been multiple questions already but I just cant seem to get any to work. Here's the steps I've taken so far;
Added the text file to my "Resources Folder"
Build action to "Content" and output directory to "Do not copy"
I then try to access the file in my code;
if (File.Exists(Properties.Resources.company_map_template))
{
MessageBox.Show("Test");
var objReader = new StreamReader(Properties.Resources.company_map_template);
string line = "";
line = objReader.ReadToEnd();
objReader.Close();
line = line.Replace("[latlong]", latitude + ", " + longitude);
mapWebBrowser.NavigateToString(line);
}
The MessageBox never appears which to me means that it cannot find the file and somewhere somehow I've done something wrong. How can I add the file into my project so I don't need to distribute with an exe whilst being able to access it in code?
I would use the following:
BuildAction to None (not needed)
and add your file to Resources.resx under files (using DragAndDrop from SolutionExplorer to opened Resources.resx)
Access to your Text:
using YOURNAMESPACE.Configuration.Properties;
string fileContent = Resources.company_map_template;
Then you're done. You don't need to access through StreamReader
I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.
Sorry for the likely noobish question, just starting to learn c#, and couldn't find anything that worked.
I'm making a text editor in c#, and so far it can open and save text files from inside the program with dialogs, but how can I make it load the text from a file that I open in windows explorer, outside of the editor, with the editor
Basically, I can already read from text files opened inside the editor, but how can i make it so that if I open a text file (and have the default program for opening text files set to my editor), it'll read it?
I saw something about getting the filename somehow and passing it as an argument, if that helps.
If I understood you correctly, you want to pass the filename/names as command line arguments ?
If you look at the Main, which starts the program you can see that it will store parameters in a string[] (string array) so if you pass arguments you can just check the args[] inside the program to get the parameters you sent in. Please ask more if you need more help !
UPDATED
As per your request if you open a file from windows explorer it will send the path of the file it to the Main method. So lets say you right click a file and choose to open it with your text editor. You have to use the path as I do below, and read the file's content. Then you can do whatever you want with the content.
class TestClass {
static void Main(string[] args) {
// Now you have all arguments in the string array
if (args.Length != 0) {
string pathToTextfile = args[0];
}
StreamReader textFile = new StreamReader(pathToTextfile);
string fileContents = textFile.ReadToEnd();
textFile.Close();
}
}
So you have a text editor coded in C#, and you want to be able to open a text file through double clicking on the file in Windows explorer. If so, basically 2 steps:
1. Your editor program must accept one argument as the file name. Carl had already given an example.
2. You need to associate *.txt files with your text editor. This could be done through editing Windows registry. please check What registry keys are responsible for file extension association
You can use the OpenFileDialog class to select a file to show in your program.
I am trying to copy contents of one xml file into another xml file. I found many examples where copying nodes is done but could not find how to just copy all the content.
Is this possible at all? If so can you please provide some direction.
Thanks
Edit:
I want to create this new xml file in the location dynamically supplied by the application's text box.
Thanks again.
If you want to replace one XML file with another, why not use File.Copy?
As a file:
string sourcefile = "somefile.xml";
string destinationfile = "anotherFile.xml";
System.IO.File.Copy(sourcefile, destinationfile);
Is File.Copy() what you're looking for?
//Introduction
Hey, Welcome.....
This is the tutorial
//EndIntro
//Help1
Select a Stock
To use this software you first need to select the stock. To do that, simply enter the stock symbol in the stock text-box (such as "MSFT").
To continue enter "MSFT" in the stock symbol box.
//EndHelp1
//Help2
Download Stock Data
Next step is to to download the stock data from the online servers. To start the process simply press the "Update" button or hit the <ENTER> key.
After stock data is downloaded the "Refresh" button will appear instead. Press it when you want to refresh the data with the latest quote.
To continue make sure you are online and press the "Update" button
//EndHelp2
First time I want to display the content between //Introduction and //EndIntro then second time the content between //Help1 and //EndHelp1 and so on.
That's a very open-ended question - what sort of file? To read binary data from it you'd usually use:
using (Stream stream = File.OpenRead(filename))
{
// Read from the stream here
}
or
byte[] data = File.ReadAllBytes(filename);
To read text you could use any of:
using (TextReader reader = File.OpenText(filename))
{
// Read from the reader
}
or
string text = File.ReadAllText(filename);
or
string[] lines = File.ReadAllLines(filename);
If you could give more details about the kind of file you want to read, we could help you with more specific advice.
EDIT: To display content from an RTF file, I suggest you load it as text (but be careful of the encoding - I don't know what encoding RTF files use) and then display it in a RichTextBox control by setting the Rtf property. Make the control read-only to avoid the user editing the control (although if the user does edit the control, that wouldn't alter the file anyway).
If you only want to display part of the file, I suggest you load the file, find the relevant bit of text, and use it appropriately with the Rtf property. If you load the whole file as a single string you can use IndexOf and Substring to find the relevant start/end markers and take the substring between them; if you read the file as multiple lines you can look for the individual lines as start/end markers and then concatenate the content between them.
(I also suggest that next time you ask a question, you include this sort of detail to start with rather than us having to tease it out of you.)
EDIT: As Mark pointed out in a comment, RTF files should have a header section. What you've shown isn't really an RTF file in the first place - it's just plain text. If you really want RTF, you could have a header section and then the individual sections. A better alternative would probably be to have separate files for each section - it would be cleaner that way.
Not sure I understand your question correctly. But you can read and write content using System.IO.StreamReader and StreamWriter classes
string content = string.Empty;
using (StreamReader sr = new StreamReader("C:\\sample.txt"))
{
content = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter("C:\\Sample1.txt"))
{
sw.Write(content);
}
Your question needs more clarification. Look at System.IO.File for many ways to read data.
The easiest way of reading a text file is probably this:
string[] lines = File.ReadAllLines("filename.txt");
Note that this automatically handles closing the file so no using statement is need.
If the file is large or you don't need all lines you might prefer to reading the text file in a streaming manner:
using (StreamReader streamReader = File.OpenText(path))
{
while (true)
{
string line = streamReader.ReadLine();
if (line == null)
{
break;
}
// Do something with line...
}
}
If the file contains XML data you might want to open it using an XML parser:
XDocument doc = XDocument.Load("input.xml");
var nodes = doc.Descendants();
There are many, many other ways to read data from a file. Could you be more specific about what the file contains and what information you need to read?
Update: To read an RTF file and display it:
richTextBox.Rtf = File.ReadAllText("input.rtf");