I'm working on a project where I want a directory to be generated according to a textfield value and I want to copy a file into the created folder...So far I could able to create the directory and copy the file but into the created folder....
try
{
string id = textBox4.Text.Trim();
// Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\"+id);
string source = null;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
source = ofd.FileName;
MessageBox.Show(source);
}
string File_name = Path.GetFileName(source);
string destination = "C:\\Users\\prashan\\Desktop\\" +
System.IO.Directory.CreateDirectory(id) + File_name;
System.IO.File.Copy(source, destination);
MessageBox.Show("Done....");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
You have the following code:
string destination = "C:\\Users\\prashan\\Desktop\\"
+ System.IO.Directory.CreateDirectory(id) + File_name;
You are concatenating the result of CreateDirectory() into your destination filename, which is incorrect. Instead, you could split this into two operations, like this:
System.IO.Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\" + id);
string destination = "C:\\Users\\prashan\\Desktop\\" + id + "\\" + File_name;
This isn't the cleanest way to do this, using Path.Combine() would be better, but I wanted to change your code as little as possible.
Small change in your code. Destination path modified to make it valid path.
try
{
string id = textBox4.Text.Trim();
Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\"+id);
string source = null;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
source = ofd.FileName;
MessageBox.Show(source);
}
string File_name = Path.GetFileName(source);
string destination = "C:\\Users\\prashan\\Desktop\\" + id +"\\"+ File_name;
System.IO.File.Copy(source, destination);
MessageBox.Show("Done....");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
Related
I have a field in a table that needs to be filled with the path and the end of the XML file to create a new file in the directory called DONE. This is made so it can tidy the directory a bit since the ones that are done don't need to be in the same directory so they are copied from one place into another.
Why is there this error?
System.NotSupportedException: 'The specified path format is not supported.'
Console.WriteLine("Ficheiro processado: " + filename);
string rootFolderPath = #"C:\XMLFiles";
string destinationPath = #"C:\XMLFiles\DONE";
string[] fileList = Directory.GetFiles(rootFolderPath);
foreach (string file1 in fileList)
{
string fileToMove = rootFolderPath + file1;
string moveTo = destinationPath + file1;
File.Move(fileToMove, moveTo);
da.SP_Insert(filename, file.Name, batch.BatchClassName, batch.Name, batch.Description, 0, "", 1, moveTo );
}
The function Directory.GetFiles(rootFolderPath); returns the full path to the file, that is filename and directory. If, like you are trying, want the filename only, you will need to extract it.
The FileInfo class is very good at extracting the Filename only of a full path.
foreach (string file1 in fileList)
{
FileInfo fi = new FileInfo(file1);
string moveTo = Path.Combine( destinationPath, fi.Name);
File.Move(file1, moveTo);
}
Rather than using string fileToMove = rootFolderPath + file1, try using System.IO.Path.Combine instead:
var fileToMove = Path.Combine(rootFolderPath, file1);
var moveTo = Path.Combine(destinationPath , file1);
GetFiles returns full paths; not just filenames:
Returns the names of files (including their paths) in the specified directory
So for the source files you don't need to combine anything, and for the target path you need to split off the filename first before combining:
foreach (string file1 in fileList)
{
string moveTo = Path.Combine(destinationPath, Path.GetFileName(file1));
File.Move(file1, moveTo);
// ...
}
This Problem was fixed this way.
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string CaminhoInicial = openFileDialog1.FileName;
Guid g = Guid.NewGuid();
FileInfo fi = new FileInfo(CaminhoInicial);
File.Copy(CaminhoInicial, CaminhoFinal + g.ToString() + fi.Extension, true);
da.SP_Inserir_Imagem(id, g.ToString() + fi.Extension);
}
}
try
{
if (dt.Rows.Count != 0)
{
string NomeImagem = dt.Rows[0][0].ToString();
pictureBox1.Image = Image.FromFile(CaminhoFinal + NomeImagem.Replace(" ", ""));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " |||| " + ex.StackTrace, "Erro", MessageBoxButtons.OK);
}
Also read this Microfost Docs post for more context.
https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=net-5.0
I am trying to move all files from rootFolderPath to destinationPath
try
{
string rootFolderPath = #"D:\Log_siteq\";
if (!Directory.Exists(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString())))
{
System.IO.Directory.CreateDirectory(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString()));
}
string destinationPath = Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString() );
string fileTypes = #"*.*";
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, fileTypes);
foreach (string file in fileList)
{
string ext = Path.GetExtension(file);
string destination = Path.Combine(destinationPath,file);
File.Move( file,destination);
MessageBox.Show(file);
MessageBox.Show(destination);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
Apparently MessageBox.Show(file); shows me my root folder path ( as is normal) but MessageBox.Show(destination); is showing me the same thing.
What gives? It just moves my file from my root folder in the same folder.Am I not getting something?
You are combining the destinationPath with the complete file path of file:
string destination = Path.Combine(destinationPath, file);
which will just overwrite the destination with the original file path (because "C:\desitnation\C:\source\filename.txt" isn't a valid path).
Instead, you need only the file name like this:
string destination = Path.Combine(destinationPath, Path.GetFileName(file));
I need to upload a CSV file to an ASP.NET application, on an Azure server. Although it works fine on my local machine, when uploading it to the server the following error is thrown:
"Process cannot access the file
'C:\inetpub\wwwroot\ImportFiles\9_11.csv' because it is being used by
another process"
My code:
string fileName = DateTime.Now.ToString().Replace(':', '_').Replace('/', '_').Replace(' ', '_') + Convert.ToString((new Random()).Next(0, 999) * (new Random()).Next(0, 999));
string path = Server.MapPath("ImportFiles") + "\\" + fileName + "" + FileImport.FileName.Substring(FileImport.FileName.IndexOf('.'));
FileImport.SaveAs(path);
string pathforSeconStream = path;
try
{
Response.Write("<script> alert('In Try Block');</script>");
bool flag = true;
int visiblemessageCount = 0;
int rollNo = 1;
StreamReader ColLine = new StreamReader(path);
string ColInputline = ColLine.ReadLine();
String[] ColsInput = ColInputline.Split(',');
ColLine.Close();
ColLine.Dispose();
string preFix = "", RollNumber = "";
StreamReader sr = new StreamReader(pathforSeconStream);
}
catch(Exception ex)
{
}
The code to generate a unique filename is wrong. Use Path.GetTempFileName.
PS never eat an exceptiion. Please remove catch (Exception ex) {};
Revision
Instead of FileImport.Save(...) just save the request in a MemoryStream and then work on it.
Is there any way i can take the data from the original location instead of copying the file to the bin/debug folder.
I am looking to send a file to my local printer. But my C# application is allowing to send file only when i copy the file to my bin/debug folder. Is there a way i can over come!!!
Codes:
private string image_print()
{
OpenFileDialog ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
string filename_noext = Path.GetFileName(ofd.FileName);
string path = Path.GetFullPath(ofd.FileName);
img_path.Text = filename_noext;
string replacepath = #"bin\\Debug";
string fileName = Path.GetFileName(path);
string newpath = Path.Combine(replacepath, fileName);
if (!File.Exists(filename_noext))
{
// I don't like to copy the file to the debug folder
// is there an alternative solution?
File.Copy(path, newpath);
if (string.IsNullOrEmpty(img_path.Text))
{
return "";
}
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}
}
}
private void button4_Click(object sender, EventArgs e)
{
string s = image_print() + Print_image();
if (!String.IsNullOrEmpty(s) &&
!String.IsNullOrEmpty(img_path.Text))
{
PrintFactory.sendTextToLPT1(s);
}
}
Try this:
private string image_print()
{
string returnValue = string.Empty;
var ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK &&
!string.IsNullOrWhiteSpace(ofd.FileName) &&
File.Exists(ofd.FileName))
{
img_path.Text = Path.GetFileName(ofd.FileName);
using (var test2 = new StreamReader(ofd.FileName))
{
returnValue = test2.ReadToEnd();
}
}
return returnValue;
}
It looks like the underlying issue is caused by these lines:
filename_noext = System.IO.Path.GetFileName(ofd.FileName); //this actually does include the extension!! It does not include the fully qualified path
...
img_path.Text = filename_noext;
...
StreamReader test2 = new StreamReader(img_path.Text);
You are getting the full file path from the OpenFileDialog then setting img_path.Text to just the file name. You are then using that filename (no path) to open the file for reading.
When you open a new StreamReader with just a filename it will look in the current directory for the file (relative to the location of the EXE, in this case bin/debug). Copying to "bin/debug" will probably not work in any other environment outside of your machine as the EXE will probably be deployed somewhere else.
You should use the full path to the selected file:
if (ofd.ShowDialog() == DialogResult.OK)
{
path = Path.GetFullPath(ofd.FileName);
img_path.Text = path;
if (string.IsNullOrEmpty(img_path.Text))
return "";//
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}
In my Windows application, I have a PictureBox and a Button control. I want to load an Image file from user from the button's OnClick event and save that image file in a folder name "proImg" which is in my project. Then I want to show that image in the PictureBox.
I have written this code, but it is not working:
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.FileName;
string filepath = "~/images/" + opFile.FileName;
File.Copy(iName,Path.Combine("~\\ProImages\\", Path.GetFileName(iName)));
picProduct.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
It's not able to save the image in the "proImg" folder.
Actually the string iName = opFile.FileName; is not giving you the full path. You must use the SafeFileName instead. I assumed that you want your folder on your exe directory also. Please refer to my modifications:
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
string appPath = Path.GetDirectoryName(Application.ExecutablePath) + #"\ProImages\"; // <---
if (Directory.Exists(appPath) == false) // <---
{ // <---
Directory.CreateDirectory(appPath); // <---
} // <---
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.SafeFileName; // <---
string filepath = opFile.FileName; // <---
File.Copy(filepath, appPath + iName); // <---
picProduct.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
You should provide a correct destination Path to File.Copy method. "~\ProImages..." is not a correct path. This example will copy selected picture to folder ProImages inside the project's bin folder :
string iName = opFile.FileName;
File.Copy(iName, Path.Combine(#"ProImages\", Path.GetFileName(iName)));
the path is relative to current executable file's location, except you provide full path (i.e. #"D:\ProImages").
In case you didn't create the folder manually and want the program generate ProImages folder if it doesn't exist yet :
string iName = opFile.FileName;
string folder = #"ProImages\";
var path = Path.Combine(folder, Path.GetFileName(iName))
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
File.Copy(iName, path);
PS: Notice the use of verbatim (#) to automatically escape backslash (\) characters in string. It is common practice to use verbatim when declaring string that represent path.
Try using picturebox.Image.Save function. In my program it is working
PictureBox.Image.Save(Your directory, ImageFormat.Jpeg)
example
pictureBox2.Image.Save(#"D:/CameraImge/"+foldername+"/"+ numbering + ".jpg", ImageFormat.Jpeg);
You write code like this.
string appPath = Path.GetDirectoryName(Application.ExecutablePath) +foldername ;
pictureBox1.Image.Save(appPath + #"\" + filename + ".jpg", ImageFormat.Jpeg);