(Newer to C#)
I have an application that I have built that copies files and folders from one location to another. I originally had issues with folders. For some reason, it would try to copy the file over without creating the directory. I solved that by adding a second section to check if the folder exists and if not create it. I am sure there is a better way to handle this, but this is what worked, so I went with it. The ultimate goal is this.
check if the file/folder exists in the destination location and is older than the source file/folder
If the file/folder doesn't exist, copy it over. If the file/folder is older than the source, copy it over.
If the file folder exists in the destination and not in the source (indicating it was deleted) move the file from the destination location to an archive folder
Below is what I have so far, and it does everything but what is described in #3 above. Any ideas in regards to how I can add the ability from #3 into the functionality, or simplify the copy of files and create the folder if it doesn't exist would be much appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileCopy
{
class Program
{
public static string dtnow = DateTime.Now.ToString("mmdd_hhmm");
public static string watch_path = string.Empty;
public static string copy_path = string.Empty;
public static string final_copy_path = string.Empty;
public static string log_folder = #"C:\copylogs";
//public static string log_file = "copy_log";
public static string log_file = Path.Combine(log_folder + "\\copy_log" + dtnow + ".txt");
public static int newer_count = 0;
public static int skip_count = 0;
public static int copy_count = 0;
public static int totalcount = 0;
public static int currentcount = 0;
static void Main(string[] args)
{
if (args == null || args.Length < 2)
{
Console.WriteLine("Invalid Syntax");
return;
}
else
{
watch_path = args[0];
copy_path = args[1];
log_start_Check(log_folder,log_file);
CopyFolder(watch_path, copy_path);
finalcount_statement();
}
}
// Log Folder check and creation
public static void log_start_Check(string log_folder, string log_file)
{
Console.Write("Checking Log Folder: ");
if (!Directory.Exists(log_folder))
{
try
{
Directory.CreateDirectory(log_folder);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create Directory" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.Write("Checking Log File: ");
//Console.WriteLine(log_file);
if (!File.Exists(log_file))
{
try
{
File.Create(log_file);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create file" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.WriteLine();
}
// Copy Folder Functions
static public void CopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(destFolder))
Directory.CreateDirectory(destFolder);
totalcount = Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories).Count();
string[] files = Directory.GetFiles(sourceFolder);
totalcount = files.Length;
foreach (string file in files)
{
string name = Path.GetFileName(file);
FileInfo source_info = new FileInfo(file);
string dest = Path.Combine(destFolder, name);
FileInfo dest_info = new FileInfo(dest);
if (File.Exists(dest))
{
try
{
if (source_info.LastWriteTime > dest_info.LastWriteTime)
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
File.Copy(file, dest, true);
Console.Write("\rFile Newer, File Copied " + dest + " ");
Console.ResetColor();
newer_count++;
}
else
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("\r** - File Exists " + dest + " ");
Console.ResetColor();
skip_count++;
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
else
{
try
{
//Console.Write("\r"+currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
File.Copy(file, dest, false);
Console.Write("\rFile Copied " + dest + " ");
Console.ResetColor();
copy_count++;
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
currentcount++;
}
string[] folders = Directory.GetDirectories(sourceFolder);
foreach (string folder in folders)
{
string name = Path.GetFileName(folder);
string dest = Path.Combine(destFolder, name);
CopyFolder(folder, dest);
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, null, null);
}
}
// Error Handling to add messages to logs
public static void error_handling(string message, string fileident, string source)
{
using (System.IO.StreamWriter myFile = new System.IO.StreamWriter(log_file, true))
{
string finalMessage = string.Format("{0}: {1} SOURCE: {3} - DEST: {2}", DateTime.Now, message, fileident, source, Environment.NewLine);
myFile.WriteLine(finalMessage);
myFile.Close();
}
}
// Final Statement
public static void finalcount_statement()
{
Console.WriteLine("");
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("Total New Files Copied: " + copy_count);
Console.WriteLine("Total Newer Files Updated: " + newer_count);
Console.WriteLine("Total Files Skipped: " + skip_count);
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("");
}
}
}
You can do it the same way around, maybe like this:
static public void ArchiveCopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(sourceFolder))
{
Directory.CreateDirectory(archivefolder + destFolder);
//Copy folder and files
}
}
}
Related
So, I've written a program which takes data from an file and process it and presents the answer. I got an error that's a bit confusing. If I call the program in the command prompt as follows: test.exe < indata.txt nothing happens, if I skip the < i.e. calls the program as: test.txt indata.txt it works fine. It also works if I call it with double in data files. Like: test.txt < indata.txt indata.txt. It's like the < token skips the following entry.
static void Main(string[] args)
{
int revolter = 0;
string[] buffer_array = new string[2000];
string path = "./";
if (args.Length == 0)
{
string read_string = System.Console.ReadLine();
buffer_array = read_string.Split(' ');
}
else
{
path += args[0];
System.Console.WriteLine(path);
StreamReader read_string = File.OpenText(path);
string s = read_string.ReadToEnd();
buffer_array = s.Split('\n');
}
}
Edit: spelling
The following shows how to create a Console program that reads data from a filename that's been specified by one of the following:
redirecting input (< infile.txt)
specifying the filename using an argument (-f:<filename> or -f:"<filename containing spaces>")
prompting the user for a filename if the filename wasn't specified
For usage, run the program with /? as the only argument.
static void Main(string[] args)
{
string filename = string.Empty;
string[] buffer = null;
if (Console.IsInputRedirected)
{
string data = Console.In.ReadToEnd();
//Console.WriteLine(data);
//set value
buffer = data.Split('\n');
}
else if (args != null && args.Length > 0)
{
foreach (var arg in args)
{
//Console.WriteLine("arg: " + arg);
if (arg == "/?")
{
Usage();
}
else if (arg.StartsWith("-f"))
{
//Console.WriteLine("arg: '" + arg + "'");
//set value
filename = arg.Substring(3).Trim();
if (!String.IsNullOrEmpty(filename))
{
if (!System.IO.File.Exists(filename))
{
Console.Error.WriteLine("Error: File '" + filename + "' doesn't exist.");
//return;
}
else
{
//read data
buffer = System.IO.File.ReadAllLines(filename);
}
}
else
{
Console.Error.WriteLine("Error: '-f' was specified, but filename wasn't specified (Note: No space is allowed between '-f:' and <filename>)");
//return;
}
}
else
{
Console.Error.WriteLine("Error: Argument '" + arg + "' unknown");
Usage();
}
}
}
else
{
do
{
Console.Write("Please enter filename ('q' to quit): ");
filename = Console.ReadLine();
//remove double quotes
filename = filename.Replace("\"", "");
if (filename == "Q" || filename == "q")
{
return;
}
else if (!System.IO.File.Exists(filename))
{
Console.Error.WriteLine("Error: File '" + filename + "' doesn't exist.");
}
else
{
//read data
buffer = System.IO.File.ReadAllLines(filename);
break;
}
} while (true);
}
//display data
DisplayData(buffer);
}
static void DisplayData(string[] buffer)
{
if (buffer != null)
{
foreach (string val in buffer)
{
Console.WriteLine(val);
}
}
}
static void Usage()
{
StringBuilder sb = new StringBuilder();
//string exeName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
string exeName = System.AppDomain.CurrentDomain.FriendlyName;
sb.AppendFormat("{0}Usage:{0}", System.Environment.NewLine);
sb.AppendFormat("{0} -f:C:\\Temp\\Test1.txt{1}", exeName, System.Environment.NewLine);
sb.AppendFormat("{0} -f:\"C:\\Temp\\Test 2.txt\"{1}", exeName, System.Environment.NewLine);
Console.Write(sb.ToString());
}
If the program is going to be called as you described (using the < filename.txt command line), the contents of the file will be available on STDIN. Your code is what you would do if your program would be called with the filename as an argument.
You can use code like this to handle text on STDIN:
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
TextReader input = Console.In;
String inpText = input.ReadToEnd();
foreach(String line in inpText.Split('\n')) {
Console.WriteLine("+++" + line);
}
}
}
}
For an input like this:
This
Is
A
Multiline
Text File
Using ConsoleApp1.exe < input.txt you get:
+++This
+++Is
+++A
+++Multiline
+++Text File
+++
Can anyone help me to resolve my healthKit capability issue for a unity app.
I am trying to add healthKit capability to my unity app. I am using BEHEALTHKIT and HealthKitBuildProcessor.cs editor class to add capability and other dependencies. Following are the code I am using .But for some reason healthkit Capability and entitlements are not adding through this code (permission parameters are adding to plist), and returning null when I print Debug.Log("newEntitlements: " + newEntitlements);Also my build failing with an error saying "provisioning profile doesn't support the HealthKit Capability"
I have already added HealthKit capability for the profile from developer.apple.com.
Unity version: 2019.4.4f1
public class HealthKitBuildProcessor : IProcessSceneWithReport
{
private static string shareString = null;
private static string updateString = null;
private static string clinicalString = null;
/*! #brief required by the IProcessScene interface. Set high to let other postprocess scripts run first. */
public int callbackOrder {
get { return 100; }
}
/*! #brief Searches for HealthKitDataTypes objects & reads the usage strings for the OnPostprocessBuild phase.
#param scene the scene being processed.
#param report a report containing information about the current build
*/
public void OnProcessScene(Scene scene, BuildReport report) {
GameObject[] rootObjects = scene.GetRootGameObjects();
foreach (GameObject obj in rootObjects) {
HealthKitDataTypes types = obj.GetComponentInChildren<HealthKitDataTypes>();
if (types != null) {
if (types.AskForSharePermission()) {
HealthKitBuildProcessor.shareString = types.healthShareUsageDescription;
}
if (types.AskForUpdatePermission()) {
HealthKitBuildProcessor.updateString = types.healthUpdateUsageDescription;
}
/*if (types.AskForClinicalPermission()) {
HealthKitBuildProcessor.clinicalString = types.clinicalUsageDescription;
}*/
}
}
}
/*! #brief Updates the Xcode project.
#param buildTarget the target build platform
#param path the path of the target build
*/
[PostProcessBuildAttribute(10)]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path) {
Debug.Log("--- BEHEALTHKIT POST-PROCESS BUILD ---");
if (buildTarget == BuildTarget.iOS) {
//string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";
//Debug.Log("BE:PROJECT PATH :" + projPath);
var projPath = PBXProject.GetPBXProjectPath(path);
var proj = new PBXProject();
proj.ReadFromString(System.IO.File.ReadAllText(projPath));
#if UNITY_2019_3_OR_NEWER
string mainTarget = proj.GetUnityMainTargetGuid();
string frameworkTarget = proj.GetUnityFrameworkTargetGuid();
Debug.Log("--- BE: UNITY_2019_3_OR_NEWER ---");
Debug.LogFormat("main target: {0}", mainTarget);
Debug.LogFormat("framework target: {0}", frameworkTarget);
#else
string targetName = PBXProject.GetUnityTargetName();
string mainTarget = proj.TargetGuidByName(targetName);
Debug.Log("---BE: ELSE UNITY_2019_3_OR_NEWER ---");
Debug.Log("main target: {0}", mainTarget);
Debug.Log("targetName: ", targetName);
#endif
bool addHealthRecordsCapability = (clinicalString != null);
//Debug.Log("addHealthRecordsCapability: ", addHealthRecordsCapability);
// Info.plist
//-----------
Debug.Log("---BE: PLIST ---");
var info = ProcessInfoPList(path, addHealthRecordsCapability);
// Entitlements
//--------------
Debug.Log("---BE: ProcessEntitlements ---");
string entitlementsRelative = ProcessEntitlements(path, proj, mainTarget, info, addHealthRecordsCapability);
#if UNITY_2019_3_OR_NEWER
// add HealthKit capability
Debug.Log("------projPath "+projPath);
ProjectCapabilityManager capabilities = new ProjectCapabilityManager(projPath, "Entitlements.entitlements", null, mainTarget);
capabilities.AddHealthKit();
Debug.Log("---BE:Capability UNITY_2019_3_OR_NEWER ---");
// add HealthKit Framework
//proj.AddFrameworkToProject(frameworkTarget, "HealthKit.framework", true);
// Set a custom link flag
//proj.AddBuildProperty(frameworkTarget, "OTHER_LDFLAGS", "-ObjC");
#else
// add HealthKit capability
Debug.Log("---ELSE BE:Capability UNITY_2019_3_OR_NEWER ---");
Debug.Log("projectPath:" + projPath);
Debug.Log("entitlementsRelative:" + entitlementsRelative);
Debug.Log("targetName:" + targetName);
ProjectCapabilityManager capabilities = new ProjectCapabilityManager(projPath, entitlementsRelative, targetName);
capabilities.AddHealthKit();
// add HealthKit Framework
proj.AddFrameworkToProject(mainTarget, "HealthKit.framework", true);
// Set a custom link flag
proj.AddBuildProperty(mainTarget, "OTHER_LDFLAGS", "-ObjC");
#endif
proj.WriteToFile(projPath);
}
}
// -------------------------------
internal static PlistDocument ProcessInfoPList(string path, bool addHealthRecordsCapability) {
string plistPath = Path.Combine(path, "Info.plist");
PlistDocument info = GetInfoPlist(plistPath);
PlistElementDict rootDict = info.root;
// // Add the keys
if (HealthKitBuildProcessor.shareString != null) {
rootDict.SetString("NSHealthShareUsageDescription", HealthKitBuildProcessor.shareString);
}
else {
Debug.LogError("unable to read NSHealthShareUsageDescription");
}
if (HealthKitBuildProcessor.updateString != null) {
rootDict.SetString("NSHealthUpdateUsageDescription", HealthKitBuildProcessor.updateString);
}
if (addHealthRecordsCapability) {
rootDict.SetString("NSHealthClinicalHealthRecordsShareUsageDescription", HealthKitBuildProcessor.clinicalString);
}
// Write the file
info.WriteToFile(plistPath);
return info;
}
internal static string ProcessEntitlements(string path, PBXProject proj, string target, PlistDocument info, bool addHealthRecordsCapability) {
string entitlementsFile;
string entitlementsRelative;
string entitlementsPath;
Debug.Log("PATH: " + path);
Debug.Log("TARGET: " + target);
String test= proj.GetUnityMainTargetGuid();
Debug.Log("TEST proj: " + test);
entitlementsRelative = proj.GetBuildPropertyForConfig(target, "CODE_SIGN_ENTITLEMENTS");
Debug.Log("entitlementsRelative: " + entitlementsRelative);
Debug.LogFormat("get build property [{0}, {1} = {2}]", target, "CODE_SIGN_ENTITLEMENTS", entitlementsRelative);
PlistDocument entitlements = new PlistDocument();
if (entitlementsRelative == null) {
string projectname = GetProjectName(info);
Debug.Log("projectname: " + projectname);
entitlementsFile = Path.ChangeExtension("Entitlements", "entitlements");
Debug.Log("entitlementsFile: " + entitlementsFile);
entitlementsRelative = Path.Combine(path, entitlementsFile);
Debug.Log("entitlementsRelative: " + entitlementsRelative);
entitlementsPath = Path.Combine(path, entitlementsRelative);
Debug.Log("entitlementsPath: " + entitlementsPath);
//proj.AddFileToBuild(target, proj.AddFile(entitlementsRelative, entitlementsRelative, PBXSourceTree.Source));
Debug.LogFormat("add build property [{0}, {1}] => {2}", target, "CODE_SIGN_ENTITLEMENTS", entitlementsRelative);
proj.AddBuildProperty(target, "CODE_SIGN_ENTITLEMENTS", entitlementsFile);
string newEntitlements = proj.GetBuildPropertyForConfig(target, "CODE_SIGN_ENTITLEMENTS");
Debug.Log("newEntitlements: " + newEntitlements);
Debug.LogFormat("=> {0}", newEntitlements);
}
else {
entitlementsPath = Path.Combine(path, entitlementsRelative);
Debug.Log("ELSE:entitlementsPath " + entitlementsPath);
}
ReadEntitlements(entitlements, entitlementsPath);
entitlements.root.SetBoolean("com.apple.developer.healthkit", true);
if (addHealthRecordsCapability) {
Debug.Log("addHealthRecordsCapability =TRUE ");
var healthkitAccess = entitlements.root.CreateArray("com.apple.developer.healthkit.access");
healthkitAccess.AddString("health-records");
}
SaveEntitlements(entitlements, entitlementsPath);
return entitlementsRelative;
}
// -------------------------------
internal static void ReadEntitlements(PlistDocument entitlements, string destinationPath) {
Debug.Log("READING Entitlements [ReadEntitlements]");
Debug.Log("READING from destinationPath [ReadEntitlements]"+ destinationPath);
if (System.IO.File.Exists(destinationPath)) {
try {
Debug.LogFormat("reading existing entitlements: '{0}'.", destinationPath);
entitlements.ReadFromFile(destinationPath);
}
catch (Exception e) {
Debug.LogErrorFormat("error reading from file: {0}", e);
}
}
}
internal static void SaveEntitlements(PlistDocument entitlements, string destinationPath) {
try {
Debug.Log("----SaveEntitlements---");
entitlements.WriteToFile(destinationPath);
}
catch (Exception e) {
Debug.LogErrorFormat("error writing to file: {0}", e);
}
}
internal static PlistDocument GetInfoPlist(string plistPath) {
// Get the plist file
PlistDocument plist = new PlistDocument();
plist.ReadFromFile(plistPath);
return plist;
}
internal static string GetProjectName(PlistDocument plist) {
string projectname = plist.root["CFBundleDisplayName"].AsString();
return projectname;
}
}
I don't know about Unity, but from Xcode when you add a capability for health kit it will update the entitlement file by itself
When trying to open a Linear Programming problem from text with Gurobi+C# it throws the error: 10012 Unable to open file "Maximize" for input.
Maximise is the first word of the text and when using
foreach (string s in args)
{
Console.WriteLine(s);
}
i get the correct output from the text file. Please help!
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
foreach (string s in args)
{
Console.WriteLine(s);
}
if (args.Length < 1)
{
Console.Out.WriteLine("Please Wait..");
return;
}
try
{
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
int optimstatus = model.Get(GRB.IntAttr.Status);
if (optimstatus == GRB.Status.INF_OR_UNBD)
{
model.GetEnv().Set(GRB.IntParam.Presolve, 0);
model.Optimize();
optimstatus = model.Get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL)
{
double objval = model.Get(GRB.DoubleAttr.ObjVal);
Console.WriteLine("Optimal objective: " + objval);
}
else if (optimstatus == GRB.Status.INFEASIBLE)
{
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
}
else if (optimstatus == GRB.Status.UNBOUNDED)
{
Console.WriteLine("Model is unbounded");
}
else
{
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Hibakód: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
you are overwriting the args parameter of your main() method with an array of all lines of the input file. That's why in
GRBModel model = new GRBModel(env, args[0]);
args[0] contains a string with the first line of your LP file instead of the filename.
I have a C# console application which reads a folder for every 15 seconds using timer. It works fine,but it pauses after nearly 8 minutes and stops reading folder. Is there any reason for that?
using System;
sing System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Data;
using System.Data.OracleClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace FolderFileReader
{
class Program
{
static void Main()
{
if (SingleInstance.SingleApplication.Run() == false)
{
return;
}
Thread thread1 = new Thread(new ThreadStart(startNewBusiness));
thread1.Start();
Thread thread2 = new Thread(new ThreadStart(startEndorsement));
thread2.Start();
Thread thread3 = new Thread(new ThreadStart(startRenewal));
thread3.Start();
Thread thread4 = new Thread(new ThreadStart(startCancellation));
thread4.Start();
Console.ReadLine();
}
private static void startNewBusiness()
{
Timer t = new Timer(ProcessNewBusinessFolder, null, 0, 5000);
}
private static void startEndorsement()
{
Timer t2 = new Timer(ProcessEndorsementFolder, null, 0, 5000);
}
private static void startRenewal()
{
Timer t3 = new Timer(ProcessRenewalFolder, null, 0, 5000);
}
private static void startCancellation()
{
Timer t4 = new Timer(ProcessCancellationFolder, null, 0, 5000);
}
private static void ProcessNewBusinessFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (New Business).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\NEW\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\NEW\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string quotationNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
quotationNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + quotationNo.ToUpper()))
{
// newDir = Directory.CreateDirectory(dest.FullName + quotationNo.ToUpper() + "\\");
System.IO.Directory.CreateDirectory(dest.FullName + quotationNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
if (quotationNo.Length > 10)
{
branchCode = quotationNo.Substring(2, 3);
}
Console.WriteLine(quotationNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + quotationNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
InsertNewBusiness(quotationNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper(), branchCode, "N");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
GC.Collect();
}
private static void ProcessEndorsementFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (Endorsement).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\ENDORSEMENT\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\ENDORSEMENT\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
UpdateEndorsement(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
// Force a garbage collection to occur for this demo.
GC.Collect();
}
private static void ProcessRenewalFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (Renewal).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\RENEWAL\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\RENEWAL\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
UpdateRenewal(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
// Force a garbage collection to occur for this demo.
GC.Collect();
}
private static void ProcessCancellationFolder(Object o)
{
Console.Clear();
Console.WriteLine("Do not close this console (Cancellation).... ");
DirectoryInfo d = new DirectoryInfo(#"E:\HNBGI\SCN_DOCS\CANCELLATION\");
DirectoryInfo dest = new DirectoryInfo(#"E:\HNBGI\QUEUED_SCN_DOCS\CANCELLATION\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
// newDir = Directory.CreateDirectory(dest.FullName + quotationNo.ToUpper() + "\\");
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
string outputFileWithPath = "";
outputFileWithPath = dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper();
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, outputFileWithPath);
UpdateCancellation(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.ReadKey();
GC.Collect();
}
public static void InsertNewBusiness(string quotationNo, string branchCode, string JobType)
{
\\Code to put Database Entry
}
public static void UpdateEndorsement(string jobNo)
{
\\Code to put Database Entry
}
public static void UpdateRenewal(string jobNo)
{
\\Code to put Database Entry
}
public static void UpdateCancellation(string jobNo)
{
\\Code to put Database Entry
}
}
}
Can anyone guess the issue?
Seems timers are collected by GC. Try to declare timers in outer scope.
private static Timer t;
private static Timer t2;
...and so on.
I have a program that converts .ppt or pptx files to png's using C# and the Microsoft.Office.Interop stuff.
It works most of the time, but under certain circumstances, it seems to fail on specific filenames for some nondescript reason.
HRESULT E_FAIL at ... Presentations.Open
It'll fail on CT_Stress_Test - Copy (16).pptx and CT_Stress_Test - Copy (11).pptx It works for (2) thru (19), but fails on only these two. My question is why?
If I were to make copies of these copies, or rename them to something else, it'll convert just fine, so I think it might have something to do with the filename.
I have the same conversion program running on my server and my local machine. My local machine (Win 7) converts the problem files just file. It's only on the server (Win 2008) that I have problems with these two filenames.
EDIT: I've found another number that doesn't work: (38)
EDIT: I formatted the strings with Path functions, and that didn't help.
EDIT: I was able to fix it by trimming all the spaces from the file names. I still want to know why this happens, though.
Here's the program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
using System.Security.Permissions;
using System.Collections.Concurrent;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static string inDir;
public static string outDir;
public static string procDir;
public static Thread[] converterThreads;
public static BlockingCollection<string> todo;
static void Main(string[] args)
{
todo = new BlockingCollection<string>();
inDir = args[0];
outDir = args[1]+"\\";
procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
converterThreads = new Thread[threadLimit];
FileSystemWatcher watcher = new FileSystemWatcher(inDir); //Watcher "thread"
watcher.Filter = "*.ppt*";
watcher.NotifyFilter = watcher.NotifyFilter | NotifyFilters.CreationTime;
watcher.IncludeSubdirectories = false;
watcher.Created += new FileSystemEventHandler(fileChanged);
watcher.EnableRaisingEvents = true;
//Create consumer threads
for(var i=0;i<threadLimit;i++)
{
Conversion con = new Conversion();
converterThreads[i] = new Thread(new ThreadStart(con.watchCollection));
converterThreads[i].Start();
}
//stay open
Console.ReadLine();
}
//Producer
private static void fileChanged(object sender, FileSystemEventArgs e)
{
if(!(e.FullPath.Contains("~$"))){ //Ignore temp files
Console.WriteLine("found =" + e.FullPath);
todo.Add(e.FullPath);
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
//Consumer
class Conversion
{
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
string dir;
static List<CorruptFile> cFiles = new List<CorruptFile>();
int retryLimit = 20;
public Conversion()
{
this.outDir = Program.outDir;
this.process = Program.procDir;
}
//Continually watches collection for files to take.
public void watchCollection()
{
while (true)
{
System.Threading.Thread.Sleep(1000);
try
{
dir = Program.todo.Take();
if (dir != null)
{
this.nameWithout = Path.GetFileNameWithoutExtension(dir);
this.nameWith = Path.GetFileName(dir);
this.output = Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(dir);
Console.WriteLine("output = " + this.output);
this.input = Path.GetFullPath(dir);
Console.WriteLine("thread took " + this.nameWith);
convertPpt();
}
}
catch (InvalidOperationException) { }
}
}
public void convertPpt()
{
try
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
moveFile();
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed " + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
Console.WriteLine("process killed");
}
}
catch (Exception e3)
{
}
try
{
if (!(cFiles.Any(x => x.fileName == dir)))
{
cFiles.Add(new CorruptFile(dir));
Console.WriteLine("file added to watch list");
Program.todo.Add(dir);
}
else
{
var found = cFiles.Find(x => x.fileName == dir);
Console.WriteLine("in watch list = " + found.fileName);
if (found.numRetry >= retryLimit)
{
Console.WriteLine(nameWith+ " to be ignored");
try
{
cFiles.Remove(found);
Console.WriteLine("File ignored");
System.Threading.Thread.Sleep(300);
Console.WriteLine("Moving: " + input);
if (File.Exists("C:\\corrupt\\" + nameWith))
{
File.Replace(input, "C:\\corrupt\\" + nameWith, null);
Console.WriteLine("file moved to C:\\corrupt\\");
}
else
{
File.Move(input, "C:\\corrupt\\" + nameWith);
Console.WriteLine("file moved to C:\\corrupt\\");
}
}
catch(Exception e5)
{
Console.WriteLine("could not move file " + e5);
}
}
else
{
Console.WriteLine("retrying file on watch list");
found.numRetry++;
Program.todo.Add(dir);
}
}
}
catch { }
}
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
if(!Directory.Exists(output)){
return;
}
Console.WriteLine("moving dir " + output);
try
{
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
class CorruptFile{
public string fileName;
public int numRetry;
public CorruptFile(string fn){
fileName = fn;
}
}
}
First up is a warning from Microsoft in this KB article here. Money quote is:
Microsoft does not currently recommend, and does not support,
Automation of Microsoft Office applications from any unattended,
non-interactive client application or component (including ASP,
ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
behaviour and/or deadlock when Office is run in this environment.
Next question is why not use OpenXML for this? Here's a simple sample to get you started which counts the number of slides in a deck.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace OpenXmlDemo
{
class PptOpenXmlDemo
{
public int PptGetSlideCount(string fileName)
{
// Return the number of slides in a PowerPoint document.
const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
int returnValue = 0;
using (Package pptPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read))
{
// Get the main document part (presentation.xml).
foreach (System.IO.Packaging.PackageRelationship relationship in pptPackage.GetRelationshipsByType(documentRelationshipType))
{
// There should be only a single relationship that refers to the document.
Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
PackagePart documentPart = pptPackage.GetPart(documentUri);
// Get the slide part from the package.
if (documentPart != null)
{
XmlDocument doc = new XmlDocument();
doc.Load(documentPart.GetStream());
// Manage namespaces to perform XPath queries.
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("p", presentationmlNamespace);
// Retrieve the list of slide references from the document.
XmlNodeList nodes = doc.SelectNodes("//p:sldId", nsManager);
if (nodes != null)
{
returnValue = nodes.Count;
}
}
// There is only one officeDocument part. Get out of the loop now.
break;
}
}
return returnValue;
}
}
}