public partial class Form1 : Form
{
string path = $#"C:\Journal";
string fileName = #"";
string compact = "";
public Form1()
{
InitializeComponent();
fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt";
compact = (path + #"\" + fileName);
}
private void btnWrite_Click(object sender, EventArgs e)
{
if(File.Exists(fileName))
{
StreamWriter myWriter = new StreamWriter(compact, true);
myWriter.WriteLine(txtDisplay.Text);
myWriter.Close();
}
else
{
StreamWriter myWriter = new StreamWriter(compact, true);
myWriter.WriteLine(txtDisplay.Text);
myWriter.Close();
}
}
I'm trying to write stuff from a multiline textbox into a file using the Monthly calender date as the file name. I keep getting an error that the directory does not exist. Not sure of the reason since i created the folder in the path, I appreciate the help.
System.IO.DirectoryNotFoundException was unhandled
It seems, you have to create directory. Another issue is
fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt";
since Short DateTime Format can contain '/' or '\' which are forbidden within file names.
public Form1() {
InitializeComponent();
// ToString(...) we don't want / or \ in the file's name
fileName = monthCalendar1.SelectionRange.Start.ToString("dd'.'MM'.'yyyy") + ".txt";
compact = Path.Combine(path, fileName);
}
private void btnWrite_Click(object sender, EventArgs e) {
Directory.CreateDirectory(Path.GetDirectoryName(compact));
// Or File.AppendAllText(compact, txtDisplay.Text);
File.AppendAllLines(compact, new string[] {txtDisplay.Text});
}
Related
im programming a application with c# and now im in trouble to build and write a .txt file with this error:
Access to the path 'E:\compex\Thursday, October 10, 2019' is denied.
and my related code is it :
private void creat_Click(object sender, EventArgs e)
{
string filename = "E:\\compex\\"+DateTime.Now.ToLongDateString() ;
string msadd = filename + "\\msadd.txt";
textpatch.Text = msadd;
Directory.CreateDirectory(filename);
filepatch.Text = filename;
using(FileStream fp = File.Create(filename))
{
log.Text = "address file created successfully";
Byte[] filepatchs = new UTF8Encoding(true).GetBytes(filename);
fp.Write(filepatchs, 0, filepatchs.Length);
log.Text = "";
log.Text = "address successfully";
}
}
whats wrong with it? is there any permission in windows or code using to get that?
private void creat_Click(object sender, EventArgs e)
{
string filename = "E:\\compex\\"+DateTime.Now.ToLongDateString() ;
string msadd = filename + "\\msadd.txt";
textpatch.Text = msadd;
Directory.CreateDirectory(filename);
filepatch.Text = filename;
using(FileStream fp = File.Create(msadd))
{
log.Text = "address file created successfully";
Byte[] filepatchs = new UTF8Encoding(true).GetBytes(filename);
fp.Write(filepatchs, 0, filepatchs.Length);
log.Text = "";
log.Text = "address successfully";
}
}
I believe, basing on your comment reply, that you meant to use msadd as the concatenated filename to write to in your using block, instead of using filename duplicated for both the directory and filename.
I want to extract the resources "cygz.dll" to the current directory where the program started right after the form is loaded.
Here is my code.
private static void extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{
Assembly assembly = Assembly.GetCallingAssembly();
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(outDirectory + "\\" + resourceName, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
}
private void Form1_Load(object sender, EventArgs e)
{
extract("myNamespace", "\\TEMP", "resources", "cygz.dll");
}
Instead of "\\TEMP", I want to extract "cygz.dll" to the current directory
If by "current directory" you mean the path for the executable file that started the application, then you can use Application.ExecutablePath like this:
System.IO.Path.GetDirectoryName(Application.ExecutablePath);
You can find more details here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.executablepath?view=netframework-4.7.2
This solved my problem
private void Form1_Load(object sender, EventArgs e)
{
string path = Environment.CurrentDirectory;
extract("myNamespace", path, "resources", "cygz.dll");
}
Hi all firstly sorry for my English but i hope you can understand me..
Im doing a project on VS2008-Smart Device Project-WinCE 5.0 Project.
I need to create text file to DATA folder which is under the main directory of program.
There is my code, there is no error messege but its not creating text file.My directory always returns null.
Whats wrong with that code?
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
try
{
StreamReader Read_File= File.OpenText(path);//Dosyayı açmaya çalış olmaz ise catch bloğuna geç
ReadFile.Close();
}
catch
{
StreamWriter Write_File= File.CreateText(path+ i.ToString()+".txt");// yeni dosya oluştur.
Write_File.Close();
}`
And heres the form2 which includes listbox and listbox shows directory for if there is a file or not..
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = path + "\\DATA";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] rgFiles = di.GetFiles();
foreach (FileInfo fi in rgFiles)
{
listBox1.Items.Add(fi.Name);
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
chosen_file = listBox1.GetItemText(listBox1.SelectedItem);
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
else
{
MessageBox.Show("HATA:Hiçbir Değer Seçilmedi!"); // That means error:no value chosen!
}
}
Your code does not prepare the path variable properly. In one case it contains a file name, in another case it contains only a path name:
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
Then you try to open a file - even though the variable does not contain a file name in the first place. If that leads to an exception, you try to create a file, but actually, you're not adding a path separator to the path. So I think your catch block should read:
StreamWriter Write_File= File.CreateText(path + "\\" + i.ToString() + ".txt");// yeni dosya oluştur.
Write_File.Close();
I am saving (uploading) file to FTP server using file upload control and .SaveAs method. But after 1st post back session values are lost. Not sure why and any work around this.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TheUser"] != null)
{
aUser = (clsUser)Session["TheUser"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)//continue only if the file control has the file
{
if (Get_and_Show_FileInformation())//if the file information was retrived and loaded into the textboxes
{
//continue with the execution
}
else
{
//error message displyed
}
}
}
protected bool Get_and_Show_FileInformation()
{
if (FileUpload1.HasFile)
{
string fName = FileUpload1.PostedFile.FileName;
string extension = Path.GetExtension(fName);
string FileName = fName.Substring(0, fName.Length - extension.Length);
string dir = uname;
string appPath = Server.MapPath("Uploads/") + dir;
FileInfo MyFileInfo = new FileInfo(appPath);
DirectoryInfo newDirectoryInfo = new DirectoryInfo(appPath);
if (!Directory.Exists(appPath))//if user is uploading to FTP_Upload first time, create a new directory for him/her
{
try
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + dir + "/" + FileName)); // ERROR here, call to this .SaveAs method causes loss of session values (Session["TheUser"])
Image2.ImageUrl = "~/Uploads/" + dir + "/" + FileName;
return true;
}
catch (Exception ex)
{
lbl_Err.Text = "<br/>Error: Error creating and saving into your space!(Error Code:XF05)";
return false;
}
}
else
{
//same code but don't create the directory
}
}
}
I need to get the path of a file which is in a specific directory.The user selects a csv file from a OpenFileDialog. If the csv file has field that ends at .txt then take the path of that file and put it in a pathfile variable. The new file has to be placed, by the user, in the same directory as the csv file.
EDIT: How do I put the path of the file in a variable ?
EDIT2: The file could be placed everywhere, for example: C://george.csv. So I want to take a txt from the directory c:// .Or if the file is here: C://Documents/anna.csv. The text has to be C://Documents/textfile.txt.
EDIT3: The csv file that the user has opened is at c://Documents/gonow.csv
The file gonow.csv is : one, two, tree, four, textfile.txt, five, six, seven.
When a field has extension .txt then the program has to go and cath the path. In this case the path is c://Documents/textfile.txt.
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
Try
string path = Path.GetDirectoryName(filename);
EDITED according to your EDIT3:
Use this function to open your csv file and get new complete filename.
private string GetFilename(string csvFilename)
{
string path = Path.GetDirectoryName(csvFilename);
string[] lines = File.ReadAllLines(csvFilename);
foreach (string line in lines)
{
string[] items = line.Split(',');
string txt = items.First(item => item.ToLower().Trim().EndsWith(".txt"));
if (!String.IsNullOrEmpty(txt))
return Path.Combine(path, txt);
}
return "";
}
iF you need to put the txt file (the generated file) in the same folder as that of the CSV file, you can store the path of the CSV file and create the txt file in theat folder.
To do this you may like to have a variable like this:
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
string FolderPath;
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
FolderPath = Path.GetDirectoryName(filename);
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
The FolderPAth variable holds the path to the folder. You can create the txt file in this folder. This means that the txt file is in the same folder as of the csv file. If you need to access this in a different method, you may declare it in relevant scope.