I'm trying to create an album and what I want to do, is to copy a picture from its original path to a specific folder and rename (the copy) right after.
Here is a piece of my code (note that "picturedir" is a path):
string PCname = Environment.UserName;
Image File;
OpenFileDialog openfile = new OpenFileDialog();
openfile.InitialDirectory = #"C:\Users\" + PCname + #"\Pictures";
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
picturedir + "\\" + "1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As seen in the last line inside the "try", I want to rename the chosen picture, simply to "1". However, this last line gives an error "Cannot create a file when that file already exists". Any ideas?
P.S.: If I do not use the last "try" line: System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1"); it does copy the chosen picture but it obviously does not rename it at all.
Here is an article about work with files.
From article:
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
}
If you use different file names, you get copy with new name.
Related
I am trying to create a console app on network version 5.0 using visual studio. The purpose is to read all the PNG files in a directory, and make a JSON file with the code:
{
"format_version": "1.16.100",
"minecraft:texture_set": {
"color": "*Filename*",
"metalness_emissive_roughness": "*Filename_mer*"
}
}
In it. And yes this is for Minecraft. The filename and the filename_mer are automatically filled in by code, but that isn't my issue.
static void Main(string[] args)
{
Console.WriteLine("Goto " + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Packages\\Microsoft.MinecraftUWP_8wekyb3d8bbwe\\LocalState\\games\\com.mojang\\resource_packs" + " And find the resource pack you want to generate files into");
string pathname = Console.ReadLine();
#region Message
Console.WriteLine();
Console.WriteLine("Looking for folder...");
#endregion
string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Packages\\Microsoft.MinecraftUWP_8wekyb3d8bbwe\\LocalState\\games\\com.mojang\\resource_packs\\" + pathname + "\\textures";
#region Message
Console.WriteLine();
Console.WriteLine("Folder found in");
Console.WriteLine(path);
#endregion
string[] directories = Directory.GetDirectories(path);
foreach (string paths in directories)
{
string[] files = Directory.GetFiles(paths);
foreach (string file in files)
{
string filenameWithType = file.Substring(file.LastIndexOf("\\") + 1);
string filename = filenameWithType.Substring(0, filenameWithType.LastIndexOf("."));
string thisPath = file.Substring(0, file.LastIndexOf("\\"));
if (filenameWithType.Substring(filenameWithType.LastIndexOf(".") + 1) == "png")
{
string newPath = thisPath + "\\" + filename + ".texture_set.json";
File.Create(newPath);
List<string> codeInFile = new List<string>();
codeInFile.Clear();
codeInFile.Add("{");
codeInFile.Add("\"format_version\": \"1.16.100\",");
codeInFile.Add("\"minecraft:texture_set\": {");
codeInFile.Add("\"color\": \"" + filename + "\",");
codeInFile.Add("\"metalness_emissive_roughness\": \"" + filename + "_mer\"");
codeInFile.Add("}");
codeInFile.Add("}");
TextWriter tw = new StreamWriter(newPath, false);
foreach (string line in codeInFile)
{
tw.WriteLine(line);
Console.WriteLine(line);
}
tw.Close();
string newPathtxt = thisPath + "\\" + filename + "_mer.png";
Bitmap bitmap = new Bitmap(file);
using (Bitmap b = new Bitmap(bitmap.Width, bitmap.Height))
{
using (Graphics g = Graphics.FromImage(b))
{
g.Clear(Color.Green);
}
b.Save(newPathtxt, ImageFormat.Png);
}
}
}
}
#region Message
Console.WriteLine("");
Console.WriteLine("All done, Your good to go!");
#endregion
Console.Read();
}
This is all my code, on the file. It reads a directory which you enter, looks through the textures file, and for each PNG file in there it creates a JSON file with the code specified earlier. Although when run the code gives me this error.
System.IO.IOException: 'The process cannot access the file 'C:\Users\https\AppData\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang\resource_packs\Vanilla_Resource_Pack_1.17.10\textures\blocks\acacia_trapdoor.texture_set.json' because it is being used by another process.'
I cannot find any answers which fit my issue, I would appreciate any help.
This is a Minecraft Bedrock edition resource pack btw, not sure if that helps.
Don't do this File.Create(newPath); or rethink your problem. It looks like a typo.
In short File.Create(newPath) is creating a FileStream and discarding it, leaving the file open and with a share lock. If you are trying to pre-create the file, at least use the using statement:
using (File.Create(newPath));
or Close
File.Create(newPath).Close();
or
File.WriteAllText(newPath, String.Empty);
or
File.WriteAllBytes(newPath, Array.Empty<byte>());
If you are just trying to create or overwrite the file StreamWriter(newPath, false) is good enough.
I Need save the txt file on a correct create folder. But its saving on C:\Nova Pasta i need save on "C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text whats is wrong ?
private void btn_SaveFile_Click(object sender, EventArgs e)
{
objSQL.Search_RGP_CadastroPrint(Convert.ToInt32(comboBox1.Text), str_list);
objSQL.SearchPrint(Convert.ToInt32(comboBox1.Text));
string path = #"C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
StreamWriter file = new System.IO.StreamWriter(path + ".txt");
file.WriteLine("---------------------------------------------------------------------------------------------------------");
file.WriteLine("Nome: " + valor.retorna_nome);
file.WriteLine("RGP: " + comboBox1.Text);
file.WriteLine("Endereço: " + valor.retorna_endereco);
file.WriteLine("Telefone: " + valor.retorna_telefone + " Celular: " + valor.retorna_celular + "\r\n");
str_list.ForEach(file.WriteLine);
file.Close();
}
Say valor.retorna_nome is "hello", and comboBox1.Text is "world". Your code does the following:
string path = #"C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text;
// -> path = "C:\Nova pasta\helloworld"
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// -> created directory "C:\Nova pasta\helloworld"
}
StreamWriter file = new System.IO.StreamWriter(path + ".txt");
// -> writes to file "C:\Nova pasta\helloworld.txt"
So it's doing exactly what you told it to. What would you like the directory to be called? And the filename?
Your String path is equals to something like that : "C:\Nova pasta\aNameXXX"
where :
aName = valor.retorna_nome
XXX = Combobox1.Text
You create a directory, this must success, but after that your file path is :
path+.txt : "C:\Nova pasta\aNameXXX.txt"
it's creating a file named (aNameXXX.txt) next to your folder.
you need to add an "\" and a name to your file to make a path like : "C:\Nova pasta\aNameXXX\FILENAME.txt"
StreamWriter file = new System.IO.StreamWriter(path + "\" + FILENAME + ".txt");
After the else block Path.Combine method combines every part and gives the file name when Console.WriteLine(result); is used. But it doesn't actually create the file with that name.
I want to get the EmployeeDetails.txt file, make a version of it (i.e. renaming the filename) and saves it to C:\Hitory folder.
How to achieve that?
Using File.Move throws FileNotFoundexception
void ModRec()
{
string filename = #"C:\Current\EmployeeDetails.txt";
string current = #"C:\Current\";
string history = #"C:\History\";
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
if (!Directory.Exists(history))
{
Directory.CreateDirectory(history);
}
}
else
{
Console.WriteLine("\t\t\tFile doesn't exist!");
Console.ReadLine();
Menu1();
}
var extension = Path.GetExtension(filename);
var fileNamePart = Path.GetFileNameWithoutExtension(filename);
var path = Path.GetDirectoryName(filename);
var version = 0;
string result;
do
{
version++;
result = Path.Combine(path, fileNamePart + "_" + version + extension);
}
while (File.Exists(result));
//File.Move(current, history);
}
Your loop at the end needs to change slightly, because
result = Path.Combine(path, fileNamePart + "_" + version + extension);
is looking in the directory where the file already is, rather than in the history directory where you want it to be, so you'll be scanning for duplicates in the wrong location. The Path.Combine therefore needs to reference the value of history:
result = Path.Combine(history, fileNamePart + "_" + version + extension);
Secondly, you cannot use Move to move a file to a directory in the same way that you can from the command line, you need to specify the two parameters as filenames, so
File.Move(current, history);
becomes
File.Move(filename, result);
The resulting code at the end of your method should therefore look like this:
do
{
version++;
result = Path.Combine(history, fileNamePart + "_" + version + extension);
}
while (File.Exists(result));
File.Move(filename, result);
Incidentally, where you test whether the file already exists, you simply call Menu1 and then carry on. Can you guarantee that that will ensure that the next thing that the user does will create a valid file? I'm guessing that it most likely cannot guarantee that, so you should exit your method at that point, or perhaps put the remainder of the body inside the fileinfo.Exists block.
That leaves the desirability of invoking a menu from inside this method, but that's a design question outside of the scope of what you've asked here.
Try this instead:
void ModRec()
{
string filename = #"C:\Current\EmployeeDetails.txt";
string current = #"C:\Current\";
string history = #"C:\History\";
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
if (!Directory.Exists(history))
{
Directory.CreateDirectory(history);
}
}
else
{
Console.WriteLine("\t\t\tFile doesn't exist!");
Console.ReadLine();
Menu1();
}
var extension = Path.GetExtension(filename);
var fileNamePart = Path.GetFileNameWithoutExtension(filename);
var path = Path.GetDirectoryName(filename);
var version = 0;
string result;
do
{
version++;
result = Path.Combine(history, fileNamePart + "_" + version + extension);
}
while (File.Exists(result));
File.Move(filename, result);
}
Path.Combine() does not touch filesystem at all. No files/folders would be ever crated.
Try File.Move(filename, history);. That is, instead of current, which is a directory, move the file (assuming filename is a full path).
I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));
I try to upload image to folder (using FileUpload) by pressing one submit button to whole form. i manage to upload the image to separate folders but i can't display it.
thank you.
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(".") + "\\images\\" + ulProj.groupCode;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
Directory.CreateDirectory(path);
fname = path + "\\" + tempFU.FileName;
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;
}
catch
{
//return;
}
Points to remember:
you should use tilde ~ operator to represent the current project
root folder.
use System.IO.Path.Combine() to combine your path and filename to get the valid complete path.
you are creating the Directory for the given path 2 times. so remove the later part where you are creating the Directory 2'nd time.
as said in the above comments as your catch block is not having anycode,
remove the try-catch block
Complete Solution:
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(#"~\images\" + ulProj.groupCode);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
fname = System.IO.Path.Combine(path,tempFU.FileName);
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;