So I'm trying to have my program read from a text file and display what is on that text file inside the command prompt, like so...
But then the program can read only one line of the file, and then throws this error exception
I've tried going over the lines of my three .cs files they complain about. I tried debugging and editing my code, but the more I do it, the worse it gets, so I'm very lost and confused and I honestly don't know what to fix at this point.
These are the lines of codes they complain about, and right below them are the actual code files.
Line 42 of FileReader.cs --->
return streamReader.ReadLine();
FileReader.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace homework2
{
#region File Reader Class
// ___________________//
// FILE READER //
//____________________//
class FileReader : Reader
{
private StreamReader streamReader;
#region File Reader File Accessing Method
// Accessing the file
public FileReader(string fileName)
{
streamReader = System.IO.File.OpenText(fileName);
if (streamReader == null)
throw new Exception("OpenRead() failed for file " + fileName);
}
#endregion
#region Read Method
// Read Method
public override string Read()
{
// get and return a single line of text
return streamReader.ReadLine();
}
#endregion
#region Close Method
// Close Method
public override void Close()
{
streamReader.Close();
}
#endregion
}
#endregion
}
Line 48 of MorgReader.cs --->
while ((Box = Wrapped.Read()) == null)
MorgReader.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using homework2;
namespace homework2
{
#region Morg Reader Class
//___________________//
// MORG READER //
//___________________//
class MorgReader : ReaderDecorator
{
MorgFactory Fact;
public MorgReader(MorgFactory fact, Reader wrapped) : base(wrapped)
{
Fact = fact;
}
public override string Read()
{
return Wrapped.Read();
}
public override void Close()
{
Wrapped.Close();
}
public Morg ReadMorg()
{
#region splitting the text string
// A way to organize the block of text
string Box = " ";
while ((Box = Wrapped.Read()) == null)
return null;
string[] Part = Box.Split(',');
#endregion
#region Displaying each line of text from Morg Reader File to Morg factory
// Translate the info from Morg file to Morg factory to the program
Morg FactMorg = Fact.CreateMorg();
FactMorg.setName(Part[0]);
#region Converting location string to its variable
// A way to convert the string location to the current variable for location
Location FactLoc;
FactLoc = new Location();
FactLoc.X = Convert.ToInt32(Part[1]);
FactLoc.Y = Convert.ToInt32(Part[2]);
#endregion
/* FactMorg.Move(FactLoc.X, FactLoc.Y); */
FactMorg.setLocation(FactLoc);
FactMorg.setMovement(Part[3]);
FactMorg.setFeeding(Part[4]);
#endregion
return FactMorg;
}
}
#endregion
}
Line 33 of Program.cs --->
while ((NewMorg = MyReader.ReadMorg()) != null)
Program.cs:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace homework2
{
#region Main Program
class Program
{
static void Main(string[] args)
// ____________________ //
// MAIN PROGRAM //
//______________________//
{
MorgReader MyReader = (new MorgReader(new MyMorgFactory(),new FileReader("morgs.txt")));
Morg NewMorg = new Morg("");
while ((NewMorg = MyReader.ReadMorg()) != null)
{
string NewMorgName = NewMorg.getName();
Location NewMorgXY = NewMorg.getLocation();
string NewMorgMovement = NewMorg.getMovement();
string NewMorgFeeding = NewMorg.getFeeding();
Console.WriteLine(NewMorgName + " " + NewMorgXY.X + " " + NewMorgXY.Y + " " + NewMorgMovement + " " + NewMorgFeeding);
MyReader.Close();
}
//MorgTypeA Morg1 = new MorgTypeA("Axel, the Axe-shaped Morg");
//MorgTypeB Morg2 = new MorgTypeB("Bael, the Dark Morg");
//MorgTypeC Morg3 = new MorgTypeC("Corona, the Light Morg");
//Simulator morgGame = new Simulator(Morg1, Morg2, Morg3);
//morgGame.run();
}
}
#endregion
}
This is my first time doing C# and I'm very new to this. I appreciate your grand help.
You are closing your reader on first iteration of your while loop.
public static void Main(string[] args)
{
//some stuff
while ((NewMorg = MyReader.ReadMorg()) != null)
{
string NewMorgName = NewMorg.getName();
Location NewMorgXY = NewMorg.getLocation();
string NewMorgMovement = NewMorg.getMovement();
string NewMorgFeeding = NewMorg.getFeeding();
Console.WriteLine(NewMorgName + " " + NewMorgXY.X + " " + NewMorgXY.Y + " " + NewMorgMovement + " " + NewMorgFeeding);
//MyReader.Close(); -> this line put it out from the while loop
}
//put it here
MyReader.Close();
//other stuff
}
Related
I'm trying to run through each line in a file which is a link. I then add to a string list all the dead links (links that return 404 or have a specific phrase printed on the page. It all works okay so far, but the only problem I currently face is it doesn't remove them from the file as I request near the end.
Why is this?
using System.Collections.Generic;
namespace dead_link_finder
{
using System;
using System.IO;
using System.Net;
using System.Threading;
static class Program
{
private static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
var fileToScan = Console.ReadLine();
var reader = new StreamReader(fileToScan);
string line;
var deadLinks = new List<string>();
while ((line = reader.ReadLine()) != null)
{
Log("Scanning: " + line, ConsoleColor.White);
using (var webClient = new WebClient())
{
try
{
var content = webClient.DownloadString(line);
if (content.Contains("text-danger"))
{
deadLinks.Add(line);
}
}
catch (WebException wex)
{
if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
{
deadLinks.Add(line);
}
}
}
}
reader.Close();
Console.WriteLine();
Console.WriteLine("Found: " + deadLinks.Count + " dead links in the collection.");
Console.WriteLine();
Thread.Sleep(5000);
Console.WriteLine("Removing the dead links, please wait...");
foreach (var deadLink in deadLinks)
{
var str = File.ReadAllText(fileToScan);
File.WriteAllText(fileToScan, str.Replace(deadLink, ""));
}
Console.WriteLine();
Console.WriteLine("Finished...");
Console.ReadKey(true);
}
}
}
You can try this. Parse the file contents into a list, save the dead links in another and then use the LINQ extension method Except() to get the difference.
This code is a bit messy and tries to do alot of things in one go. You should probably split it up into more manageable pieces like ReadFile(), CheckLinks() and WriteFile() or something.
using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Linq;
namespace dead_link_finder
{
static class Program
{
private static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
var fileToScan = Console.ReadLine();
var links = File.ReadAllLines(fileToScan);
var deadLinks = new List<string>();
var webClient = new WebClient();
foreach (var link in links)
{
try
{
var content = webClient.DownloadString(link);
if (content.Contains("text-danger"))
{
deadLinks.Add(link);
}
}
catch (WebException wex)
{
if (wex.Status == WebExceptionStatus.NameResolutionFailure )
{
deadLinks.Add(link);
}
}
}
Console.WriteLine();
Console.WriteLine("Found: " + deadLinks.Count + " dead links in the collection.");
Console.WriteLine();
Thread.Sleep(5000);
Console.WriteLine("Removing the dead links, please wait...");
var justTheGoodLinks = links.Except(deadLinks);
File.WriteAllLines(fileToScan, justTheGoodLinks);
Console.WriteLine();
Console.WriteLine("Finished...");
Console.ReadKey(true);
}
}
}
I am trying to create user defined function which uses class defined in pcapDotNet.Core.Dll file. My c# Code is as below:
using System;
using System.IO;
using System.Collections.Generic;
using PcapDotNet.Core;
using System.Linq;
using System.Runtime.InteropServices;
using RGiesecke.DllExport; //GANESH
using System.Runtime.InteropServices;//GANESH
using System.Reflection;
namespace ObtainingAdvancedInformationAboutInstalledDevices
{
class Program1
{
/*
static void Main(string[] args)
{
Program1 var1 = new Program1();
var1.checkDevice();
}*/
public Program1()
{
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}
static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
String dllName = new AssemblyName(args.Name).Name + ".dll";
var assem = Assembly.GetExecutingAssembly();
String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));
if (resourceName == null) return null; // Not found, maybe another handler will find it
using (var stream = assem.GetManifestResourceStream(resourceName))
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
//**************************************USER DEFINED FUNCTIONS START*********************
[DllExport("checkFunction", CallingConvention = CallingConvention.Cdecl)]//GANESH
public static int checkFunction()
{
Program1 worker1 = new Program1();
worker1.checkDevice();
return 0;
}
void checkDevice()
{
// Retrieve the interfaces list
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
Console.WriteLine(" inside checkDevice\n");
// Scan the list printing every entry
for (int i = 0; i != allDevices.Count(); ++i)
DevicePrint(allDevices[i]);
}
// Print all the available information on the given interface
private static void DevicePrint(IPacketDevice device)
{
// Name
Console.WriteLine(device.Name);
// Description
if (device.Description != null)
Console.WriteLine("\tDescription: " + device.Description);
// Loopback Address
Console.WriteLine("\tLoopback: " +
(((device.Attributes & DeviceAttributes.Loopback) == DeviceAttributes.Loopback)
? "yes"
: "no"));
// IP addresses
foreach (DeviceAddress address in device.Addresses)
{
Console.WriteLine("\tAddress Family: " + address.Address.Family);
if (address.Address != null)
Console.WriteLine(("\tAddress: " + address.Address));
if (address.Netmask != null)
Console.WriteLine(("\tNetmask: " + address.Netmask));
if (address.Broadcast != null)
Console.WriteLine(("\tBroadcast Address: " + address.Broadcast));
if (address.Destination != null)
Console.WriteLine(("\tDestination Address: " + address.Destination));
}
Console.WriteLine();
}
}
}
My python code is as below:
class gooseDriver():
"""A class that creates windows form by importing IED.MainWindow()"""
def __init__(self, ipAddress, port):
self.hllDll = WinDLL (r"C:\WORK\IEC61850\gooseThread1\gooseThread1\bin\x64\Debug\gooseThread1.dll")
self.hllDll.checkFunction()
print("Goose Message Started\n")
def main():
IED = gooseDriver("192.168.0.20", 102)
print("GooseDriver is called\n")
if __name__ == '__main__':
main()
when I tried to call checkFunction from python giving error as "OSError: [WinError -532462766] Windows Error 0xe0434352". This is because function is using LivePacketsDevice class from pcap files. I have embedded pcapDotNet.Core.Dll file while generating DLL as reference. Can anybody suggest what is solution for this issue please.
After lot of trial, it started working when i placed pcapDotNet DLL files into folder where Python interpreter exists. Dont know what is reason? can anybody know on this please.
I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?
I've been trying to write this in order to list my folders , the append part doesn't work and it rewrites the whole thing , also if i try to list something else without exiting the app it gives the the "file is in use" error which does not make sense to me because I used close() at end of each loop.
I have checked almost all Microsoft documents and lots of posts here but couldn't find my answer .
The Picture that shows the Error I get
Thanks a lot in advance !
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;
namespace Anime_Lister
{
public partial class Anime0Lister : Form
{
public void Appen()
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path0save.Text, true))
{
DirectoryInfo directory = new DirectoryInfo(path0tb.Text);
DirectoryInfo[] directory0Arr = directory.GetDirectories();
foreach (DirectoryInfo dir in directory0Arr)
{
String Parent = Convert.ToString(dir.Parent);
String Name = Convert.ToString(dir.Name);
String Root = Convert.ToString(dir.Root);
File.AppendAllText(path0save.Text, Parent);
File.AppendAllText(path0save.Text, " || ");
File.AppendAllText(path0save.Text, Name + System.Environment.NewLine);
File.AppendAllText(path0save.Text, Root + System.Environment.NewLine);
}
}
}
public void Writer()
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path0save.Text))
{
DirectoryInfo directory = new DirectoryInfo(path0tb.Text);
DirectoryInfo[] directory0Arr = directory.GetDirectories();
foreach (DirectoryInfo dir in directory0Arr)
{
String Parent = Convert.ToString(dir.Parent);
String Name = Convert.ToString(dir.Name);
String Root = Convert.ToString(dir.Root);
file.Write(Parent);
file.Write(" || ");
file.WriteLine(Name);
file.WriteLine(Root);
}
}
}
public void Browser()
{
FolderBrowserDialog address = new FolderBrowserDialog();
if (address.ShowDialog() == System.Windows.Forms.DialogResult.OK)
path0tb.Text = address.SelectedPath;
}
public void Browser2()
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
path0save.Text = saveFileDialog1.FileName;
}
}
public Anime0Lister()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//_____________________________________________________________List
{
try
{
if (existing0file.Checked == true)
{
Appen();
}
else
{
Writer();
}
}
catch (Exception Fail)
{
MessageBox.Show(Fail.Message);
}
}
}
}
}
A disposable object like a StreamWriter should be always enclosed in a Using Statement to be sure, that even in case of exception, the object is closed and its unmanaged resources freed for reuse. The language gives you a specific statement for this, (Using Stetement) but, in your specific case, if you open a file using a StreamWriter then you can't use the File.AppendAllText because this method tries itself to open the file and find it 'in use' by the previous opened StreamWriter
public void Appen()
{
using(System.IO.StreamWriter file = new System.IO.StreamWriter(path0save.Text, true))
{
DirectoryInfo directory = new DirectoryInfo(path0tb.Text);
DirectoryInfo[] directory0Arr = directory.GetDirectories();
foreach (DirectoryInfo dir in directory0Arr)
{
// No need for those Convert.ToString.
// The DirectoryInfo properties used are already strings.
file.Write(dir.Parent);
file.Write(" || ");
file.WriteLine(dir.Name);
file.WriteLine(dir.Root);
// or just in one line
//file.WriteLine(string.Concat(dir.Parent,
// " || ",
// dir.Name,
// Environment.NewLine,
// dir.Root));
}
}
}
The same using statement should be applied to the Writer method...
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;
}
}
}