everytime i change a file such as a .rft or .txt i want it to display the name in the title for e.g RFT Editor:docment.rft
here the code i am using atm
this.Text = "RFT Editor:" + saveFileDialog1.FileName;
hope someone can help
Your question is poorly worded. You don't describe how the result you are getting is different from what you'd like it to be.
I can only guess the problem is that "RFT Editor:" + saveFileDialog1.FileName gives you a file name with an entire path, and to get "RFT Editor:docment.rft" as in your example you'd need "RFT Editor:" + System.IO.Path.GetFileName(saveFileDialog1.FileName) instead.
Assuming you need this:
...
...
// Save clicked inside, not Cancel
if(saveFileDialog1.openDialog() == DialogResult.OK)
{
// this.Text is same as only Text - in case of current class (matter of choice)
Text = "RTF Editor: " + savefileDialog1.FileName;
...
...
}
Related
So I am currently trying to do this question for tafe but am having trouble getting it to add text to the file after the first time.
"Create an application that at start up asks the user to choose an output file using a Save File Dialog Window. The application to have a “Write to File” button that when clicked will take a name and age that the user has entered into two text boxes and write them directly to the file. The user can repeat the button click action as often as they wish."
This is my current code for it:
private void Form4_Load(object sender, EventArgs e)
{
saveFileDialog1.Title = ("Choose Save Location");
saveFileDialog1.ShowDialog();
}
private void btnSendToFile_Click(object sender, EventArgs e)
{
string strName = txtName.Text;
string strAge = txtAge.Text;
string strTitles = ("Name \t\t Age");
string strCombined = strTitles + "\n" + (strName + "\t\t" + strAge);
System.IO.StreamWriter OutFile;
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
OutFile = System.IO.File.CreateText(saveFileDialog1.FileName);
OutFile.WriteLine(strCombined);
OutFile.Close();
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
StreamWriter AddFile = File.AppendText(saveFileDialog1.FileName);
AddFile.Write(strCombined);
}
I'm not sure if I should be doing a loop or not and this is the form itself, https://gyazo.com/e2c4170d46295d6f92a35026e1f2304b
Any help is appreciated, Thanks in advance
For what you're doing you absolutely don't need to work with streams or anything that low level (you don't need to call the create methods on files and use a stream returned by it). You can directly use the methods that write or append to the file and handle all of this for you.
For example using AppendAllText will do everything for you (managing the streams, flushing and closing them, appending at the end, creating the file if it doesn't exist etc etc).
so you can replace all of this code :
System.IO.StreamWriter OutFile;
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
OutFile = System.IO.File.CreateText(saveFileDialog1.FileName);
OutFile.WriteLine(strCombined);
OutFile.Close();
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
with
File.AppendAllText(saveFileDialog1.FileName, strCombined);
I have no idea what you're doing in the code that follows it (calling appendtext, i assume you're thinking you need to append after creating?) in any case you don't need it. So if you just want to append all the text of "strcombined" at the end of the file each time you click the whole function should look like :
private void btnSendToFile_Click(object sender, EventArgs e)
{
string strName = txtName.Text;
string strAge = txtAge.Text;
string strTitles = ("Name \t\t Age");
string strCombined = strTitles + "\n" + (strName + "\t\t" + strAge);
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
File.AppendAllText(saveFileDialog1.FileName, strCombined);
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
}
Also as a side comment i would rewrite all of it as such for readability, these are suggestions and not hard rules:
1) Removed hungarian notation (Don't add a prefix to your variable to indicate it's type, it's generally frowned upon)
2) Removed a lot of the temporary variables that aren't really needed (used once in the same local function)
This makes for a much smaller and very readable function:
private void btnSendToFile_Click(object sender, EventArgs e)
{
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
File.AppendAllText(saveFileDialog1.FileName,"Name \t\t Age"+ "\n" + txtName.Text + "\t\t" + txtAge.Text);
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
}
This is my first question and english is not my first language so please be comprehensive with me.
Basicaly my program save data in a .js file. I use SaveFileDialog method to set the path and use .FileName to set the... well file name. Here's how I do it
private void parcourir_Click(object sender, EventArgs e)
{
SaveFileDialog exportJSFile = new SaveFileDialog();
// Getting year, month and day of the day to generate the file name
DateTime date = DateTime.Today;
exportJSFile.FileName = date.Year + "_" + date.Month + "_" + date.Day + "_ct.js";
if (exportJSFile.ShowDialog() == DialogResult.OK)
{
this.JSfilePath.Text = exportJSFile.FileName;
}
}
Then I use the StreamWriter to write data in my file
// Writing the first block (header) of data into the .js file
System.IO.StreamWriter objWriterFirstBlock;
objWriterFirstBlock = new System.IO.StreamWriter(#JSfilePath.ToString());
objWriterFirstBlock.Write(firstBlock);
objWriterFirstBlock.Close();
When I debug it, I get the above error message coming from this line:
objWriterFirstBlock = new System.IO.StreamWriter(#JSfilePath.ToString());
I tried the same command without the #, same result. When I use the dialog box to set the path name, the path is displayed in a textbox and it seems right. When I chek the value of JSfilePath.ToString() in the debugger, it shows a path like:
#JSfilePath = {Text = "C:\\Users\\admin\\Documents\\2014_3_5_ct.js"}
Can someone tell me what's wrong
Assuming that JSfilePath is a TextBox, it appears that you are using the ToString() method on the TextBox itself, which will not return what you are looking for.
If you change it to JSfilePath.Text this should fix it for you:
objWriterFirstBlock = new System.IO.StreamWriter(JSfilePath.Text);
Can i get the full path from a filename such as get the full directory path from test.txt, Or is there a way i can save it
The reason im asking this is im making a application like Notepad++ some of you may of heard of it. When changing the tab control tab I want the form's text to be the full directory while the tabs text is just filename.format
My so far code
private void tabControl1_TabIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab.Text.StartsWith("New"))
{
int count = tabControl1.TabCount - 1;
this.Text = tabControl1.Controls[count].Text + " - My Note 1.0";
}
//It is a directory and i need to make the forms text the path here?
}
You can use System.IO.Path.GetFullPath:
var fullPath = Path.GetFullPath("test.txt");
If you pass in a short file name, it is expanded to a long file name.
If c:\temp\newdir is the current directory, calling GetFullPath on a file name such as test.txt returns c:\temp\newdir\test.txt.
And if you want to get path from that you use System.IO.Path.GetDirectoryName
var path = Path.GetDirectoryName(fullPath)
I think you should probably keep the full path and get the filename from the full path rather than the other way around. The key is to use a type representing a document, and let the tab view that document. If each tab refers to a document, and each document knows its full path, then you can get the short filename from the documents full path.
public class Document
{
public string FullPath { get; set; } // Full path to file, null for unsaved
public string FileName
{
get { return Path.GetFileName(FullPath); }
}
}
When a new tab is focused, get the document for the active tab and set the forms title from the FullPath of the document.
private void tabControl1_TabIndexChanged(object sender, EventArgs e)
{
Document activeDoc = GetDocumentFromActiveTab();
// Update win title with full path of active doc.
this.Text = (activeDoc.FullPath ?? "Unsaved document") + " MyApp" + version;
}
EDIT:
The key here is of course the method GetDocumentFromActiveTab() which isn't shown. You need to implement the data structures that manage your documents, and connects them to tabs. I did not include that in the answer, you need to try yourself. One idea is to make a type representing the entire application state including all tabs and documents.
public class Workspace
{
private Dictionary<SomeTypeOfView, Document> documentsOpenInViews;
// Methods to register a document to a tab, get document for a tab
// remove tab+document when tab is closed etc.
}
// not sure if this is what you want
say your filename with path is
string strFFL = #"C:\path\filename.format";
Console.WriteLine(System.IO.Path.GetFileName(strFFL)); //->filename.format
Console.WriteLine(System.IO.Path.GetDirectoryName(strFFL)); //-> C:\path
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
I think this is actually backwards. I think you want to keep a full path to the file and be able to display the filename only on the tab. So I think you want Path.GetDirectory name.
From: http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
string filePath = #"C:\MyDir\MySubDir\myfile.ext";
string directoryName;
int i = 0;
while (filePath != null)
{
directoryName = Path.GetDirectoryName(filePath);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
filePath, directoryName);
filePath = directoryName;
if (i == 1)
{
filePath = directoryName + #"\"; // this will preserve the previous path
}
i++;
}
/*
This code produces the following output:
GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir') returns 'C:\'
GetDirectoryName('C:\') returns ''
*/
Please tell me why file.Delete(gpath) is not working?
i will be very thankful to you :) If there is any error on this code then tell about that error.This code can be wrong so please tell me.
string gpath;
string path=#"c:\Users\Adam\Desktop\";
string name="file";
string f="";
int i=0;
string ext=".txt";
while(File.Exists(path + name + f + ext))
{
i++;
f = i.ToString();
}
gpath = path + name + f + ext;
button2.Enabled = true;
File.Create(gpath);
File.Delete(gpath);//why there is an Error??
File.Create returns a FileStream which you haven't disposed of, so there's an open handle to the file. When you try and delete a file with that has a handle attached to it, you'll get an error saying that the file is in use.
I don't know why you're trying to delete the file straight after creating it so if you explain what you're ultimately attempting to do, there's likely a better way of going about it.
What I am trying to do is to read in a file to a richTextBox automatically with the OnSelectedIndexChange method. There arent any errors, it just flat out doesnt work. Heres the code that I am working with
public void comboBox1_OnSelectedIndexChanged(object sender, EventArgs e)
{
string selectedPath = comboBox1.SelectedItem.ToString();
if (File.Exists(#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt"))
{
try
{
Thread.Sleep(0500);
System.IO.StreamReader textFile = new System.IO.StreamReader(#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt");
richTextBox1.Text = textFile.ReadToEnd();
textFile.Close();
}
catch
{
MessageBox.Show("Error: File cannot be opened!", "Error");
}
}
else
{
MessageBox.Show("No comment was found in this folder", "Alert");
}
}
Just for fun, lets have you try something. First, replace the following line:
if (File.Exists(#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt"))
with this:
if(File.Exists(string.Format("C:\\Mavro\\MavBridge\\{0}\\Comment.txt", selectedPath)))
It looks like you had an extra space ("\\ " + "Comment"), so I'm sure that's why it never hits this block of code. Also, anytime you have an object that needs to be closed/disposed, more often than not it implements IDisposable, meaning you should encapsulate the object within a using block:
Thread.Sleep(0500);
try
{
using(System.IO.StreamReader textFile = new System.IO.StreamReader(string.Format("C:\\Mavro\\MavBridge\\{0}\\Comment.txt", selectedPath)))
{
richTextBox1.Text = textFile.ReadToEnd();
}
}
catch
{
MessageBox.Show("Error: File cannot be opened!", "Error");
}
However, this can be simplified even further by bypassing the StreamReader entirely and using System.IO.File.ReadAllText instead:
richTextBox1.Text = System.IO.File.ReadAllText(string.Format("C:\\Mavro\\MavBridge\\{0}\\Comment.txt", selectedPath));
Well, one problem comes from the fact that you have:
#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt"
Since you are using a verbatim string (the # at the beginning), you do not need to put double slashes.
For the rest, make sure your file exists.
Later edit: also I am not sure if you copy/pasted in a rush or something like that, but did you actually put the catch block inside the try ?
1) What is the error you see?
2) Are you positive the file exists?
3) Are you positive the path created by your code is the path you are expecting?
4) Why are you sleeping the thread?
5) Why not just use File.ReadAllText?
6) File.Exists will return false if the code is running with permissions that do not have access to a file, even if the file does exist. Does the user your code is running as, have permissions?
true if the caller has the required permissions and path contains the
name of an existing file; otherwise, false. This method also returns
false if path is null, an invalid path, or a zero-length string. If
the caller does not have sufficient permissions to read the specified
file, no exception is thrown and the method returns false regardless
of the existence of path.
and
The Exists method returns false if any error occurs while trying to
determine if the specified file exists. This can occur in situations
that raise exceptions such as passing a file name with invalid
characters or too many characters, a failing or missing disk, or if
the caller does not have permission to read the file.
Get rid of # before each string. Your directory as it currently is uses actual double slashes instead of C:\Mavro\MavBridge. Use single slashes with \ or go with # at the beginning, but don't use both.
Also, I would strongly suggest using Path.Combine instead of concatenating pieces together like that.