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.
Related
I am trying to output the file address of an item selected in a combobox. But i keep getting the Directory address of the project and not the item itself. Please help. Here is my Code:
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (availableSoftDropBox.SelectedItem.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
txtFlashFile.Text = openFileDialog1.FileName;
}
else
{
string fileName;
fileName = Path.GetFullPath((string)availableSoftDropBox.SelectedItem);
string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\" + (fileName);
txtFlashFile.Text = fullPath;
I'm not quite sure what you want to achieve, but using FileInfo instead of Path.GetFullPath might help.
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
const string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\";
string selection = (string)availableSoftDropBox.SelectedItem;
var fileInfo = new FileInfo(fullPath + selection);
string text = fileInfo.FullName;
if (selection.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
text = openFileDialog1.FileName;
}
}
txtFlashFile.Text = text;
}
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});
}
I am trying to copy one image from one location to another location using File.Copy() function but it gives the process can not access exception,any one can please help on this bellow is the code block.I have attached screenshot for exception.
private void btnUpload_Click(object sender, EventArgs e)
{
string SourcePath;
string RootDrive;
string DestPath;
string fileName;
fileName = "";
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Image to Upload";
ofd.Filter = "Jpg|*.jpg|Jpge|*.jpge|Gif|*.gif";
ofd.FileName = null;
if (ofd.ShowDialog() != DialogResult.Cancel)
{
fileName = ofd.FileName;
}
ofd.Dispose();
DestPath = Directory.GetCurrentDirectory() + #"\Uploads\PropertyImages\";
string destFile = System.IO.Path.Combine(DestPath, fileName);
if (!System.IO.Directory.Exists(DestPath))
{
System.IO.Directory.CreateDirectory(DestPath);
}
System.IO.File.Copy(fileName, destFile, true);
}
catch (Exception ae)
{
MessageBox.Show(ae.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
It's probably because you are attempting to copy the file to itself. The call to Combine(), as you have it, is just returning fileName. Change the following line:
string destFile = System.IO.Path.Combine(DestPath, fileName);
to
string destFile = System.IO.Path.Combine(DestPath, System.IO.Path.GetFileName(fileName));
private void btn_add_image_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Choose a file";
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = " JPEG Files (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg|All Files (*.*)|*.*";
openFileDialog1.ShowDialog();
string file_name = openFileDialog1.FileName;
string filename2 = openFileDialog1.SafeFileName;
pictureBox1.Image = Image.FromFile(file_name);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
string[] extension = getExtension("images\\" + userid);
if (File.Exists("images\\" + userid + extension[0]))
{
File.Delete("resimler\\" + userid + extension[0]);
}
}
catch (Exception)
{
MessageBox.Show("İmage cannot find");
}
I want to Change File name and save , so i wrote this code if file exists , than delete file and save the choosen with userid name but i cant do change name and save file
if (File.Exists(#"\path\to\source"))
{
File.Move(#"\path\to\source",#"\path\to\destination")
}
I think both your problems can me handled with this bit of code.
System.IO.File.Move("old_file_name_path", "new_file_name_path");
This moves the file to a new filename. Take a look here: File.Move
But, I really don't get what you are asking here:
i wrote this code if file exists , than delete file and save the
choosen with userid name but i cant do change name and save file
Can you be more specific?
Thanks All
private void btn_save_Click(object sender, EventArgs e)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
string source = openFileDialog1.FileName;
string[] extension = getExtension(source);
string destination = "images\\" + userid + extension[0];
System.IO.File.Move(source, destination);
pictureBox1.Image = Image.FromFile("images\\" + userid + extension[0]);
}
i have created a small ftp program in c# using winforms but when i try to create this in wpf it is showing me an error "Value cannot be null. Parameter name:fileName", The code works fine in winform.
here is the code:
public partial class Ftp : UserControl
{
string filePath;
public Ftp()
{
InitializeComponent();
}
//Clear TextBox when clicked
#region textBox clear
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
//TextBox tb = (TextBox)sender;
//tb.Text = string.Empty;
//tb.GotFocus -= TextBox_GotFocus;
}
#endregion
//Open File Dialog
private void browser_click(object sender, RoutedEventArgs e)
{
#region File Dialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.CheckFileExists = true;
dlg.DefaultExt = ".txt";
dlg.Filter = "JPEG Files (*.txt)|*.txt|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
dlg.FileName = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Open document
string filename = dlg.FileName;
pathtext.Text = filename;
}
#endregion
}
//Upload the File to FTP
private void Upload_click(object sender, RoutedEventArgs e)
{
#region Upload files
if (filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
browser.IsEnabled = false;
try
{
FileInfo fileInfo = new FileInfo(filePath);
string fileName = fileInfo.Name.ToString();
WebRequest requestFTP = WebRequest.Create("ftp://" + hosttext.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(usertext.Text, passtext.Password);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
MessageBox.Show("File Uploading Is SuccessFull...");
}
catch (Exception ep)
{
MessageBox.Show("ERROR: " + ep.Message.ToString());
}
browser.IsEnabled = true;
filePath = "";
hosttext.Text = usertext.Text = passtext.Password = pathtext.Text = "";
}
#endregion
}
}
You never set your filePath variable, so it's null. In browser_click you need to do something like
if (result == true)
{
// Open document
string filename = dlg.FileName;
filePath = filename; //added this line
pathtext.Text = filename;
}
Also, you think you have handled your invalid string here:
if (filePath == "")
but at that point filePath = null.
Instead, use if (string.IsEmptyOrNull(filePath))