I have registered a program in windows explorer right click menu using this link. .NET-Shell-Extension, It works fine. But my problem is I want to target XML file, If I right click on that file it will load that XML file and open fileDialog to choose folder and create folder and sub-folder according to the structure of the XML file. It looks fine when I tasted it on shell server. I tried to register with this following code but its not appearing when I click on any XML file.
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using SharpShell.Attributes;
using SharpShell.SharpContextMenu;
using System.Xml;
namespace ClassLibrary1
{
[ComVisible(true)]
[COMServerAssociation(AssociationType.ClassOfExtension, ".xml")]
public class Class1 : SharpContextMenu
{
protected override bool CanShowMenu()
{
return true;
}
protected override ContextMenuStrip CreateMenu()
{
var menu = new ContextMenuStrip();
var createFolder = new ToolStripMenuItem
{
Text = "Create Folder",
};
createFolder.Click += (sender, args) => myFunction();
menu.Items.Add(createFolder);
return menu;
}
private void myFunction()
{
var ofd = new OpenFileDialog();
foreach (var filePath in SelectedItemPaths)
{
if (ofd.ShowDialog() != DialogResult.Cancel)
{
string fullPath = ofd.FileName;
using (XmlTextReader reader = new XmlTextReader(fullPath))
{
var basePath = filePath + "/";
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
var baseDirPath = Path.Combine(basePath + reader.Name);
Directory.CreateDirectory(baseDirPath);
break;
case XmlNodeType.Text:
Directory.CreateDirectory(basePath + reader.Name + "/" + reader.Value);
break;
}
}
}
}
}
}
}
}
Related
I'm using the Ookii Vista folder dialog for ease of use, and I have this code going on which is called from a button:
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Ookii.Dialogs;
private string LoadDirectories()
{
VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK && fbd.SelectedPath.Contains("U000"))
{
return fbd.SelectedPath;
}
else
{
MessageBox.Show("Folder must be root assembly, which has U000 in name");
}
return string.Empty;
}
Currently, if the user does not pick a folder with U000 in the name, the dialog will close, but I want it to stay open until user either cancels or sets the correct folder path. I can't find this anywhere.
A simple realization of your needs (Add a while):
Used nuget: Ookii.Dialogs.Wpf
private string LoadDirectories()
{
VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
while (true)
{
if (fbd.ShowDialog() == false)
{
break;
}
else if (fbd.SelectedPath.Contains("U000"))
{
return fbd.SelectedPath;
}
else
{
MessageBox.Show("Folder must be root assembly, which has U000 in name");
}
}
return string.Empty;
}
output:
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 haven't really written anything outside of Powershell in a long time, and I know this is ugly, but I can't seem to figure out why my new PDF is not adding the page numbers. I pulled the example from this itext kb.
I tried to make this basic app so people in the office could add the page numbers to PDF's. Here's what I have so far. It will create the new PDF (duplicate of the original), but it's not adding the page numbers.
Basically they use button1 to find their PDF via the Windows File Explorer dialog. It just stores the filename in a textbox. The second button is the "save" and should take the src file and make a copy of the src with only adding the page number at the bottom of the file (or anywhere at this point).
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace PDFManipulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file;
}
catch (System.IO.IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
private void button2_Click(object sender, EventArgs e)
{
Stream myStream;
//SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
string SRC = textBox1.Text;
string DEST = saveFileDialog1.FileName;
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
Document doc = new Document(pdfDoc);
int numberOfPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
// Write aligned text to the specified by parameters point
doc.ShowTextAligned(new Paragraph("page " + i + " of " + numberOfPages),559, 806, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
}
doc.Close();
}
}
MessageBox.Show("PDF Page Numbering Added!", "Pages Added",MessageBoxButtons.OK);
Application.Exit();
}
}
}
I'm a dumb dumb. The x,y coordinates were off as the value 812 for the height is off the page.
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);
}
}
}
}
For some reason after my SaveFileDialog, my app will never show the MessageBox. Is there something I'm missing? Or is this a threading issue?
I run the application as a Windows Form application using VS 2010 Express.
I do not get any exceptions.
To add: When I step through the code, all seems to go well. Which is weird, so I believe it is a timing issue.
Pointed out by LarsTech and others, the MessageBoxes do show up, however the focus is gone; in other words the MessageBox is pushed behind other windows or minimized. This is a problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
namespace SpeedDating
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string filename = "test.test"; // args[0];
string ext = filename.Substring(filename.LastIndexOf('.'));
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
}
catch (NotSupportedException ex)
{
MessageBox.Show("Probably removed the original file.");
}
}
else
{
MessageBox.Show("No path found to write to.");
}
MessageBox.Show("I came here and all I got was this louzy printline");
}
}
}
I tried this one and it showed right away:
MessageBox.Show(new Form() { WindowState = FormWindowState.Maximized, TopMost = true }, "You clicked Cancel button", "Cancel");
Try this for your Message Box.
MessageBox.Show(this,"Probably removed the original file.");
I created a new project and pasted your code and it works for me. Make sure you have done a full rebuild before running. Also, with this line:
dialog.FileName = DateTime.Now.ToString(format) + "." + ext;
The dialog box will have a file name to begin with. Therefore, only hitting the cancel button (assuming you don't clear the save dialog first) will trigger the message box. Either way, I got the message box to pop up by failing your IF test either way. Your code looks alright.
Perhaps you should put the SaveFileDialog in a using to ensure its disposal prior to the MessageBox call:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
namespace SpeedDating
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string filename = "test.test"; // args[0];
string ext = filename.Substring(filename.LastIndexOf('.'));
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Title = "SpeedDating App by K.Toet";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
}
catch (NotSupportedException ex)
{
MessageBox.Show("Probably removed the original file.");
}
}
else
{
MessageBox.Show("No path found to write to.");
}
}
MessageBox.Show("I came here and all I got was this louzy printline");
}
}
}