"The given path's format is not supported" - c#

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

Related

Store multiple int in a .txt file, each time on a new line

Sorry for the bad title, i didn't know how to explain it better. I just started in Csharp so its probably a dumb mistake.
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = "CPU Usage" + " " + (int)cpuCounter.NextValue() + "%";
string[] usageCPUay = { label1.Text };
System.IO.File.WriteAllLines(#"C:\Users\Filip\Desktop\CPUOutput.txt", usageCPUay);
}
So this is the code I have issues with and can't understand how to fix it. I tried with streamwriter but I got the same issues. I want to make the output the cpuCounter gives to store in a txt file. But every time it just writes the latest CPU Usage and not every one. Like this wrong output. I want it to type all the cpu usages it got and store them like that but every new one in a separate line.
Let's analyze your code:
you have a method, in the body you have label1.text which is text I assume, a string.
then you have got an array of strings, but this array contains only a single element, which is label1.text, then you write in the text file the array, which contains only a single element.
3 errors I see:
1.- the array contains a single element, therefore you are only storing a single line.
2.- at the end of the string that you are meant to record in the text file you should add "\n" for a new line.
3.- I understand from https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netcore-3.1#System_IO_File_WriteAllLines_System_String_System_String___ that it creates the file as new, therefore you may be deleting what you already have.
Solution:
Like in the example that was presented to you in the link, I would do the following:
label1.Text = "CPU Usage" + " " + (int)cpuCounter.NextValue() + "%\n";
string[] usageCPUay = { label1.Text };
if (!File.Exists(path))
{
// Create a file to write to.
File.WriteAllLines(path, usageCPUay);
}
else{
File.AppendAllText(path, usageCPUay);}

Display Filename in button text

How to get the string in the button text?
private void btn_open_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
ReadCSV(openFileDialog1.FileName);
btn_open.Text = "filename here";
string targetdirectory = "D:\\Projects";
string filename = Path.GetFileNameWithoutExtension(target directory);
}
thanks for your help
When you select a file using OpenFileDialog, the OpenFileDialog.FileName contains the full path of the file selected.
Path.GetFileNameWithoutExtension() does just that, getting the file name without extension. However you need to pass an actual file path, not a directory. If you pass a directory path, it will simply retrieve the innermost directory name which is not what your desired outcome.
So what you should do is;
Get file name from OpenFileDialog.
Pass that to the Path.GetFileNameWithoutExtension() method.
Set the resulting string as the button text.
Also the correct usage of ShowDialog() is to check the return value; it returns true if the user clicked OK button, and false otherwise.
if(openFileDialog1.ShowDialog() == true)
{
string file = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
btn_open.Text = file;
}

Save text to a text file already created

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

Get full path from short file name

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 ''
*/

c# change the form title by the savefile name.extension

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;
...
...
}

Categories