using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;
using System.Management;
namespace test_code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenamePngFiles(folderDlg.SelectedPath);
}
private void RenamePngFiles(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in System.IO.Directory.EnumerateFiles(directoryPath, "*.png", new EnumerationOptions()))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
}
Above is my code and I am not sure why i am not able to remove the above error. I tried all sorts of namespace and i cannot of get rid of it. I am using .netframework 4.7.2.
AS you can see all I am trying to do is rename all the files in a folder including subfolder to append with # and a number which keep on increasing depending on the number of files in a folder.
Combined with the comments above, I made the following changes.
Updated:
Modify all png files in the selectedPath.
RenameAllPngFiles(folderDlg.SelectedPath);
The following are custom functions:
Rename all png files :
private void RenameAllPngFiles(string directoryPath) {
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath)) {
RenameCurrentPng(item.FullName);
}
}
Rename all png files in the current directory:
private void RenameCurrentPng(string directoryPath) {
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png")) {
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
Get the addresses of all subfolders :
private DirectoryInfo[] GetDirectoryInfos(string directoryPath) {
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
If you have questions about my code, please comment below and I will follow up.
Related
Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.
I am fairly new to C# so i don't know how to attack this problem. I have this code, that generates the form so a pop up box comes up and lets you select the folder the user wants to select. The problem is that after its selected it doesn't give an option to hit enter or hit ok so that the rest of my code can use that folder as a path to execute the remainder of what i want to do.
This is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.ReadKey();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}
What generates the form to come is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace FolderBrowserDialogSampleInCSharp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I'm assuming that i either have to add in a button in the form design as "enter" or "ok."
Could i just have this so that as soon as the user selects the folder and hits ok the program proceeds to store that as the user selected path?
The answer i was searching for:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.Read();
Close();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}
The problem is that when copying the files in the netscan.zip file to the usb.
It unzip all to root.
This is how the files looks in KHtemp folder:
c:\Data\install\ <- Files
c:\Data\info <- Files
c:\Knowhow.exe
But when the copying is done i looks like this on the usb
\knohow.exe
\data\
\intall\
\info\
I can not find out what iam doing wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KHupdater
{
public partial class Install : Form
{
public Install()
{
InitializeComponent();
Close.Visible = false;
}
// COPY
#region copy
public static void CopyFolder(string sourcePath, string destinationPath)
{
Directory.CreateDirectory(destinationPath);
// Copy files first.
foreach (var sourceFile in Directory.GetFiles(sourcePath))
{
string destFile = Path.Combine(destinationPath, Path.GetFileName(sourceFile));
File.Copy(sourceFile, destFile, true);
}
foreach (var sourceSubPath in Directory.GetDirectories(sourcePath))
{
string destPath = Path.Combine(destinationPath, sourceSubPath.Substring(sourcePath.Length));
CopyFolder(sourceSubPath, destPath);
}
}
#endregion
private void Start_Click(object sender, EventArgs e)
{
Start.Visible = false;
Loadingbar.Visible = true;
string tempfolder = "C:\\KHtemp";
string tempfile = #"c:\KHtemp\Update.zip";
// If the 'tempfolder' exists it will be deleted
if (Directory.Exists(tempfolder))
{
Directory.Delete("c:\\KHtemp", true);
}
Loadingbar.Value = (10);
// Make Folder and download file
if (!Directory.Exists(tempfolder))
{
Directory.CreateDirectory(tempfolder);
}
WebClient webClient = new WebClient();
webClient.DownloadFile("http://67.327.195.57/netscan.zip", #"c:\KHtemp\Update.zip");
Loadingbar.Value = (50);
// Unrar files in to 'tempfolder'
ZipFile.ExtractToDirectory(tempfile, tempfolder);
// Del rar file from 'tempfolder'
File.Delete("c:\\KHtemp\\Update.zip");
// !?
Loadingbar.Value = (70);
// Copy files to USB
var StartupPath = Application.StartupPath;
var root = System.IO.Path.GetPathRoot(StartupPath);
// Copy All files from 'tempfolder' to root of the USB
foreach (var sourceFilePath in Directory.GetFiles(tempfolder))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(root, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
CopyFolder(tempfolder, root);
}
Loadingbar.Value = (90);
//// Del 'tempfolder'
Directory.Delete("c:\\KHtemp", true);
////
this.Loadingbar.Style = System.Windows.Forms.ProgressBarStyle.Blocks;
// Show message when done
Loadingbar.Value = (100);
label1.Text = "Update is Done";
Close.Visible = true;
}
private void Close_Click(object sender, EventArgs e)
{
var StartupPath = Application.StartupPath;
var root = System.IO.Path.GetPathRoot(StartupPath);
var Knowhowfile = "Knowhow.exe";
var Knowhow = Process.Start(root + Knowhowfile);
Environment.Exit(1);
}
}
}
You need to copy each folder as well - something like this will work:
public static void CopyFolder(string sourcePath, string destinationPath)
{
Directory.CreateDirectory(destinationPath);
// Copy files first.
foreach(var sourceFile in Directory.GetFiles(sourcePath))
{
string destFile = Path.Combine(destinationPath, Path.GetFileName(sourceFile));
File.Copy(sourceFile, destFile, true);
}
foreach(var sourceSubPath in Directory.GetDirectories(sourcePath))
{
string destPath = Path.Combine(destinationPath, Path.GetFileName(sourceSubPath));
CopyFolder(sourceSubPath, destPath);
}
}
You should call CopyFolder(tempFolder, root)
Please note that it is not tested, you need to debug the CopyFolder method to verify e.g. destPath
You need to identify the current item in loop is File or Directory.
If it's a file then write a code of copy and if it's a directory then create it manually by using System.IO.Directory.CreateDirectory("");
HI I have several xml files , I select them using open file dialog, then delete duplicate data from those files and now I wanted every individual files to saved as.bak file I can select multiple files and delete those data from files but dont no how to save those files after deleting.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO.Path;
namespace XML_Deletes
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
//single indivual file
var doc = XDocument.Load(#"C:\\Users\IT-Administrator\Desktop\21.xml");
doc.Root.Elements("Incident")
.GroupBy(s => (string)s.Element("Comment"))
.SelectMany(g => g.Skip(1))
.Remove();
//doc.Save(#"C:\Users\IT-Administrator\Desktop\22.xml");
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "XML files(.xml)|*.xml|all Files(*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
{
if (!String.Equals(Path.GetExtension(openFileDialog1.FileName),
".xml",
StringComparison.OrdinalIgnoreCase))
{
// Invalid file type selected; display an error.
MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.",
"Invalid File Type",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
}
} }
}
}
Are you looking for XDocument.Save?
doc.Save(#"C:\\Users\IT-Administrator\Desktop\21.xml");
That's already in your code (though its commented out?). Are you having issues saving?
I am trying to show the version numbers of both old and new to user then copy the new version. When I was trying copy the file after showing the version information I am getting the following exception
The process cannot access the file 'C:\Auto TEC\Common.dll' because it is being used by another process.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Diagnostics;
namespace copyfile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceDirectory = #"E:\newversion\Auto TEC";
string targetDirectory = #"C:\Auto TEC";
Copy(sourceDirectory, targetDirectory);
label3.Text = "sucess";
loadAssembyNames();
}
void f2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
public static void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it's new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
string _errMsg;
//private AssemblyInformation _info;
private void getfilenames(string directoryPath, int location)
{
string[] path = new string[25];
int count = 0;
foreach (string file in System.IO.Directory.GetFiles(directoryPath))
{
path[count] = file;
count++;
}
Assembly asm = null;
for (int i = 0; i < count; i++)
{
try
{
//asm = Assembly.LoadFrom(path[i]);
asm = Assembly.LoadFile(path[i]);
if (asm != null)
{
if (location == 1)
{
listBox1.Items.Add(asm.GetName().Name + asm.GetName().Version.ToString());
}
else
{
listBox2.Items.Add(asm.GetName().Name + asm.GetName().Version.ToString());
}
}
}
catch (Exception err)
{
this._errMsg = err.Message;
}
}
asm = null;
GC.Collect();
}
private void Form1_Load(object sender, EventArgs e)
{
loadAssembyNames();
}
private void loadAssembyNames()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
getfilenames(#"C:\Auto TEC", 1);
getfilenames(#"E:\newversion\Auto TEC", 2);
}
}
}
How do I unload the assembly information from object?
There's no way to unload an individual assembly without unloading all of the appdomains containing it. So you should use different appdomain foreach of your assemblies.
More info :
Unloading an assembly
Assembly Unload? Use AppDomain.Unload instead
Once assembly is loaded it cannot be unloaded.
You have one option to copy the bytes to the memory and then load using Assembly.Load(byte[]). Also you may use FileVersionInfo which is much easier.
You can't unload an assembly once it's loaded into your AppDomain. The only way to accomplish this is to load the assembly in a separate AppDomain, and unload the entire AppDomain.
As soon as you reference an assembly or type from that assembly within your AppDomain, it will be loaded into that AppDomain and not released.
In .Net, if you load the assembly in the same AppDomain as the application, then it's not possible to unload it (this includes loading it for reflection only). If you need to inspect the assembly internals, I recommend using Mono.Cecil (http://www.mono-project.com/Cecil).
I think i am not in time to answer this questions but i had the same problem and for future reference you just need to use "FileVersionInfo.GetVersionInfo"
system.Diagnostics
and thats it, this option will not load the assembly just its information and you will be able to replace the file.