Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Here is my code:
private void Instalarbtn_Click(object sender, RoutedEventArgs e)
{
string MinecraftFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/.minecraft";
string destinationFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "system.zip");
FastZip FastZip = null;
if (Directory.Exists(MinecraftFolder + "/temp"))
{
Directory.Delete(MinecraftFolder + "/temp", true);
}
FastZip.ExtractZip(MinecraftFolder + "/bin/minecraft.jar", MinecraftFolder + "/temp/Minecraft", String.Empty);
try
{
Directory.Delete(MinecraftFolder + "/temp/Minecraft/META-INF", true);
}
catch (DirectoryNotFoundException e1)
{
}
FastZip.ExtractZip(destinationFile, MinecraftFolder + "/temp", String.Empty);
FastZip.CreateZip(MinecraftFolder + "/bin/minecraft.jar", MinecraftFolder + "/temp/Minecraft", true, String.Empty);
if (Directory.Exists(MinecraftFolder + "/temp"))
{
Directory.Delete(MinecraftFolder + "/temp", true);
MessageBox.Show("Instalado correctamente", "Instalador");
}
}
(Sorry for the long code)
If helps i´m trying to extract a .jar, add content at the same folder and repack again.
It doesnt works
Anyone knows because don´t works?
And if know the solution, please tell me
Thanks
EDIT: With this code i want unzip all folders from minecraft.jar, then add some files with overwrite the files and repack again
Since you're not specific about your problem, I'll choose the first issue I see:
string destinationFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "system.zip");
You might not have write permissions for the directory this will refer to. This could be one cause of failure. Run your application as administrator, or change the directory you will write to, and if that works, this may very well be your problem.
Please be more specific...
Change this and debug, try to see the error description of the exception:
catch (Exception e1)
{
MessageBox.Show(e1.ToString());
}
The tag shows C#.
If so, your folder separators are wrong.
If in doubt, use Path.Combine.
Here's a version using that (and a few extra variables, so the code is easier to read):
private void Instalarbtn_Click(object sender, RoutedEventArgs e) {
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string MinecraftFolder = Path.Combine(appFolder, "minecraft");
string destinationFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "system.zip");
FastZip FastZip = null;
string minecraftTemp = Path.Combine(MinecraftFolder, "temp");
if (Directory.Exists(minecraftTemp)) {
Directory.Delete(minecraftTemp, true);
}
string minecraftBin = Path.Combine(MinecraftFolder, "bin");
string minecraftTempMinecraft = Path.Combine(minecraftTemp, "Minecraft");
FastZip.ExtractZip(minecraftBin, minecraftTempMinecraft, String.Empty);
string minecraftTempMinecraftMETAINF = Path.Combine(minecraftTempMinecraft, "META-INF");
try {
Directory.Delete(minecraftTempMinecraftMETAINF, true);
} catch (DirectoryNotFoundException e1) {
}
FastZip.ExtractZip(destinationFile, minecraftTemp, String.Empty);
string minecraftBinMinecraftJar = Path.Combine(minecraftBin, "minecraft.jar");
FastZip.CreateZip(minecraftBinMinecraftJar, minecraftTempMinecraft, true, String.Empty);
if (Directory.Exists(minecraftTemp)) {
Directory.Delete(minecraftTemp, true);
MessageBox.Show("Instalado correctamente", "Instalador");
}
}
I have no idea if it works. I do not have or use this FastZip utility, and I did not even bother trying to understand the logic.
You probably have to create a new instance of FastZip, you're currently assigning null to it.
FastZip FastZip = null;
Replace with:
FastZip FastZip = new FastZip();
I recommend you change your FastZip instance's name also (currently called FastZip to more easily recognizable fastZip to distinct it from calling FastZip's (possible) static methods instead of the methods of the actual instance.
FastZip fastZip = new FastZip();
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
My app is a 32 bit .Net VS 2017 app. File.Exists always returns false in my app. Either running in VS, deployed locally, or as admin. Running on a Windows 10 64 bit system. Paths are good because the File.Copy works (but always since File.Exist isn't working. I don't want File.Copy to run unless file doesn't exist. Maybe suggestions for a workaround if I can't get it to work? File permissions shouldn't be a problem since the file is in the Documents folder. Maybe a better SpecialFolder to use than MyDocuments? Any help would be appreciated. Thanks in advance. Code below.
// Class variables
public static string appPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"\\Lottery Analyzer Expert International";
public static string dbPath = appPath + "\\database\\";
public static string dbFile = "Histories.sqlite";
// Class method
public void copyInputFiles_db()
{
string dest = dbPath + dbFile;
string src = Application.StartupPath + "\\database\\" + dbFile;
if (!File.Exists(dest)) { }
{
File.Copy(src, dest, true); // if input files not found in appPath copy from install folder
bool do_download = true;
DialogResult dialogResult2 = MessageBox.Show(
"The history database was copied from the application's startup to it's working dirctory. This happens when first running " +
"the application or the history file is missing. Would you like to update that file from the web?",
"Download file?", MessageBoxButtons.YesNo);
if (dialogResult2 == DialogResult.Yes)
{
do_download = true;
}
else if (dialogResult2 == DialogResult.No)
{
do_download = false;
}
if (do_download)
downloadAllTheHistoryFIles_db();
}
printTextFiles();
}
You know that the code below the if is always executed?
if (!File.Exists(dest)) { } // << the { } is the IF scope
{ // <- this is a new scope also, but not part of the if..
File.Copy(src, dest, true);
bool do_download = true;
// *SNIP*
}
Remove the { } behind the if
I'm currently working on a dll library project.
if (!Directory.Exists(MenGinPath))
{
Directory.CreateDirectory(MenGinPath + #"TimedMessages");
File.WriteAllLines(MenGinPath + #"TimedMessages\timedmessages.txt", new string[] { "Seperate each message with a new line" });
}
else if (!File.Exists(MenGinPath + #"TimedMessages\timedmessages.txt"))
{
Directory.CreateDirectory(MenGinPath + #"TimedMessages");
File.WriteAllLines(MenGinPath + #"TimedMessages\timedmessages.txt", new string[] { "Seperate each message with a new line" });
}
As you can see if the statement Directory.Exists is false a specific directory (MenGinPath) will be created. However, if the same path, with another file in addition is false, the second functions will be called.
My question is the following: is there any way to make this shorter?
Because as you can see I'm calling 2 times the same functions:
Directory.CreateDirectory(MenGinPath + #TimedMessages\timedmessages.txt
and
File.WriteAllLines(MenGinPath + #"\TimedMessages\timedmessages.txt"))
Any help would be welcome!!
You don't need to check if directory exists because Directory.CreateDirectory automatically creates the directory if it does not exists and does nothing if the directory already exists.
Also, do not include the filename when creating the directory. Yes, it wont error but just for clarity sake.
Another one is to use Path.Combine instead of hardcoding the path. This will improve readability of your code.
So, here's what I can come up with:
string dir = Path.Combine(MenGinPath, #"Groups\TimesMessages");
string file = Path.Combine(dir, "timedmessages.txt");
// this automatically creates all directories in specified path
// unless it already exists
Directory.CreateDirectory(dir);
//of course, you still need to check if the file exists
if (!File.Exists(file) {
File.WriteAllLines(filePath, new string[] { "Seperate each message with a new line" });
}
/* or if file exists, do your stuff (optional)
* else {
* //do something else? maybe edit the file?
* }
*/
You can make your code shorter given the fact that CreateDirectory does nothing when the directory exists. Moreover do not pullute your code with all that string concatenations to create the path and the file names.
Just do it one time before entering the logic using the appropriate method to create filenames and pathnames (Path.Combine).
string messagePath = Path.Combine(MenGinPath, "TimedMessages");
string fileName = Path.Combine(messagePath, "timedmessages.txt");
// call the create even if it exists. The CreateDirectory checks the fact
// by itself and thus, if you add your own check, you are checking two times.
Directory.CreateDirectory(messagePath);
if (!File.Exists(fileName)
File.WriteAllLines(fileName, new string[] { "Seperate each message with a new line" });
Would something like this work?
string strAppended = string.Empty;
if (!Directory.Exists(MenGinPath))
{
strAppended = MenGinPath + #"Groups\timedmessages.txt";
}
else if (!File.Exists(MenGinPath + #"TimedMessages\timedmessages.txt"))
{
strAppended = MenGinPath + #"TimedMessages\TimedMessages.txt";
}
else
{
return;
}
Directory.CreateDirectory(strAppended);
File.WriteAllLines(strAppended, new string[] { "Seperate each message with a new line" });
I have found that it is a great idea to reuse blocks of code like this instead of hiding them in if statements because it makes code maintenance and debugging easier and less prone to missed bugs.
It seems the only difference between the 2 cases is the path. So just get only this path in your if-else
const string GroupsPath = #"Groups\timedmessages.txt";
const string TimedMessagesTxt = #"TimedMessages\TimedMessages.txt";
string addPath = null;
if (!Directory.Exists(MenGinPath)) {
addPath = GroupsPath;
} else if (!File.Exists(Path.Combine(MenGinPath, TimedMessagesTxt))) {
addPath = TimedMessagesTxt;
}
If (addPath != null) {
Directory.CreateDirectory(Path.Combine(MenGinPath, addPath));
File.WriteAllLines(Path.Combine(MenGinPath, TimedMessagesTxt),
new string[] { "Seperate each message with a new line" });
}
Note: Using Path.Combine instead of string concatenation has the advantage that missig or extra \ are added or removed automatically.
I have a method that is helps to Create a Directory ifNotExist and Save the path of the File ,...
Now I have a little problem, There is an Exception casted when Directory.CreateDirectory(savePath); Runs. and I can't still get it right. I would like to know what I am doing wrong and how to fix it. Anyone Subjections is welcome. Thanks
Here is My Method:
protected void ASPxUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
String savepath = String.Format("{0}{1}\\", MapPath(#"~\TicketUploads\"), Session["lastcallid"]);
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
e.UploadedFile.SaveAs(savefile);
String urlPath = String.Format("{0}{1}\\{2}", #"~\TicketUploads\", Session["lastcallid"], e.UploadedFile.FileName);
fault_detail fltdet = session.GetObjectByKey<fault_detail>(Convert.ToInt32(Session["lastcallid"]));
fltdet.hasattachment = "Y";
fltdet.AttachUrl = urlPath;
fltdet.Save();
}
}
For more details of What I trying to do:
It simple allows the web server to identify the ID of the log user. and With that ID, We should therefore create a folder in Ticketuploads Folder. Which is like we are trying to create 2 folders at the same time. That is why I use: "{0}{1}\\"
please try this
string sessionVariable = Convert.ToString(Session["lastcallid"]);
string path = Path.Combine(MapPath(#"~\TicketUploads\"), sessionVariable);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Also
I have Add Administration Permission to the Folder. As a Local user with IIS System. user Add Example: IIS_IUSRS(Username\IIS_IUSRS) That's it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have project and I want to make a receipt of a buyer and write it on the notepad but my problem is when I install my application on other computer. the notepad is not opening and nothing happen when button click
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\Receipt.txt");
using (StreamWriter w = new StreamWriter(path))
{
string x=label1.Text.Replace(" ",string.Empty);
string x2 = label2.Text.Replace(" ", string.Empty);
string x3 = label3.Text.Replace(" ", string.Empty);
string x4 = label4.Text.Replace(" ", string.Empty);
string x5 = label5.Text.Replace(" ", string.Empty);
w.Write("***************OFFICIAL RECEIPT*************** \r\n", true);
w.Write("\r\n"+"\r\n"+"***************Buyer Information*************"+"\r\n");
w.Write(x+"\r\n",true);
w.Write(x2+ "\r\n", true);
w.Write(x3 + "\r\n", true);
w.Write(x4 + "\r\n", true);
w.Write(x5+ "\r\n", true);
w.Write("\r\n" + "***************PURCHASE ITEM*****************" + "\r\n");
w.Write("ITEM QUANTITY PRICE" + "\r\n");
for (int xx = 0; xx<listBox1.Items.Count;xx++ )
{
w.Write(listBox1.Items[xx].ToString()+"\r\n");
}
w.Write("_____________________________________________"+ "\r\n");
w.Write("TOTAL " + totalprice+"\r\n"+"\r\n");
w.Write(" -THIS IS YOUR OFFICIAL RECEIPT- "+"\r\n");
w.Write(" THANK YOU FOR BUYING! ");
w.Close();
}
Process.Start("notepad.exe", path);
Try Changing
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\Receipt.txt");
to
var path = Application.StartupPath + "\\Receipt.txt";
.
And also
Process.Start("notepad.exe", path);
to
Process.Start("notepad.exe", "\"" + path + "\"");
Changing this helped some people in some cases
providing quotes might help in case if the problem is because of empty spaces in folder names
Assuming this is winforms, as a test, change your catch block to look like this:
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
throw;
}
If it's working on your dev box and not on another computer, I'd be willing to bet you have a permissions issue. Just try the code above and see what message you get. Then you can figure out what is wrong and how to fix it.
I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
The place where I got the error is at File.Copy(sourceDir + "\\" + toBeCopied[i] ....
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is.
Can you take a look at the Path.Combine method on MSDN? This will help make sure all your entire path doesn't have extra \'s where they shouldn't be.
i.e. Path.Combine(sourceDir, toBeCopied[i])
If you are still getting an error, let me know what the value if the above.
Does the target path up to the file name exist? File.Copy() will not create any missing intermediate path, you would need to do this yourself. Use the debugger to see both the source and target paths you are creating and make sure the source exists and the target exists at least up to the parent of the target file.
You do not show where toBeCopied is created. It looks like you are probably running past the end of the values that are set in the click event, and trying to copy a bunch of files with empty names.
You should add this to the beginning of your click event
toBeCopied = new string[listView1.SelectedItems.Count];
Also (as others have noted) instead of
sourceDir + "\\" + toBeCopied[i]
you should use
Path.Combine(sourceDir, toBeCopied[i])
Assuming both sourceDir and targetDir exist (which you can and should check), you might be doubling up a trailing \. When building paths, you should use Path.Combine.
File.Copy(Path.Combine(sourceDir, toBeCopied[i]), Path.Combine(targetDir, toBeCopied[i]), true);
Borrowing from Henk's loop, but I'd add the file & directory checks, since it is the path not found errors that need checking/creating that the OP has the problem with.
for (int i = 0; i < toBeCopied.Length; ++i)
{
string sourceFile = Path.Combine(sourceDir, toBeCopied[i]);
if(File.Exists(sourceFile))
{
string targetFile = Path.Combine(targetDir, toBeCopied[i]);
if(!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
File.Copy(sourceFile, targetFile, true);
}
refreshToolStripMenuItem_Click(sender, e)
}