Rename OST File in C# - c#

I have this code in C# that works fine in some users.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace Rename_OST
{
class Program
{
static public void killOutlook()
{
try
{
string process = "OUTLOOK";
foreach (Process outLook in Process.GetProcessesByName(process))
{
outLook.Kill();
}
}
catch (Exception) { }
}
static public void startOutlook()
{
try
{
//busca el path del Outlook
Process.Start("OUTLOOK");
}
catch (Exception)
{
Console.WriteLine("Could'n open Outlook. Please start Outlook and press any key.");
Console.ReadKey();
}
}
static public void replaceOutlook()
{
string ostPath = "C:\\Users\\" + Environment.UserName + "\\AppData\\Local\\Microsoft\\Outlook\\";
string ostFile = "Outlook.ost";
string ostNewFile = "Outlook.ost.txt";
try
{
if (!File.Exists(ostPath + ostNewFile))
{
File.Move(ostPath + ostFile, ostPath + ostNewFile);
}
else
{
File.Delete(ostPath + ostNewFile);
File.Move(ostPath + ostFile, ostPath + ostNewFile);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("The OST file was not found.");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Closing Outlook client...");
killOutlook();
Console.WriteLine("Replacing OST file name...");
Thread.Sleep(5000);
replaceOutlook();
Thread.Sleep(5000);
Console.WriteLine("Starting Outlook client...");
startOutlook();
}
}
}
The code only works if the file is named outlook.ost. How can I change the code in order that rename the OST file search regardless of the name.
Thanks in advance

Iterate through the files in the directory to check if they're .OST and then rename them.
// GET ALL FILES IN DIRECTORY
string[] fileEntries = Directory.GetFiles(ostPath);
// CHECK EACH FILE
foreach (string fileName in fileEntries)
{
// IS IT AN OST?
if (Path.GetExtension(fileName).ToLower() == ".ost")
{
// RENAME LOGIC HERE, EXAMPLE:
File.Move(fileName, fileName + ".OLD");
}
}
You should be careful hard coding the .OST path like that. Something like the below would be better:
string ostPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), #"Microsoft\Outlook");
Edit
An better example of replaceOutlook(). Still needs work but better illustrates how this works for OP.
static public void replaceOutlook()
{
// OST PATH
string ostPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), #"Microsoft\Outlook");
// LIST OF FILE PATHS IN OST PATH
string[] fileEntries = Directory.GetFiles(ostPath);
try
{
// CHECK EACH FILE PATH
foreach (string fileName in fileEntries)
{
// IS IT AN OST?
if (Path.GetExtension(fileName).ToLower() == ".ost")
{
// TRY AND DELETE OLD FILE, WON'T THROW EXCEPTION IF FILE DOESN'T EXIST
File.Delete(fileName + ".OLD");
// RENAME FILE
File.Move(fileName, fileName + ".OLD");
}
}
}
catch
{
// Blah blah....
}
}

Related

How to read and show content from multiple text file?

As the question, how to show content from multiple text file? I would like to read all the content from the path show in the console with 1 press button and store into a variable. Currently it only can read 1 by one. I'm self learner and begineer for the C# currently.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ListFileInDirectory(#"C:\Users\liewm\Desktop\SampleFile");
Console.WriteLine("Press enter to continue");
Console.Read();
}
private static void ListFileInDirectory(string workingDirectory)
{
string[] filePaths = Directory.GetFiles(workingDirectory);
String line;
foreach (string filePath in filePaths)
{
Console.WriteLine(filePath);
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader(filePath);
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line= sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
}
You can try like this
private static void ListFileInDirectory(string workingDirectory)
{
string[] filePaths = Directory.GetFiles(workingDirectory);
String line;
foreach (string filePath in filePaths)
{
Console.WriteLine(filePath);
try
{
//it returns string[]
var allText = System.IO.File.ReadAllLines(filePath);//opens a text file, reads all text and closes the text file.
foreach(var str in allText)
{
//Do what you want.
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
static void Main(string[] args)
{
//ListFileInDirectory(#"C:\Users\albto\Documents\_projetos\MultiplesFiles\MultiplesFiles\_arquivos");
ListFileInDirectory(#"C:\Users\liewm\Desktop\L907C524_1x");
Console.WriteLine("Press enter to continue");
Console.Read();
}
private static void ListFileInDirectory(string workingDirectory)
{
string[] filePaths = Directory.GetFiles(workingDirectory);
List<string> allLines = new List<string>();
foreach (string filePath in filePaths)
{
try
{
//stores the files address
allLines.Add(filePath);
//stores file lines
allLines.AddRange(System.IO.File.ReadAllLines(filePath));
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
//shows all stored lines
allLines.ForEach(Console.WriteLine);
Console.ReadLine();
}

system io file not found exception/ error handling

I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:
"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"
Please someone help me to do the error handling.
Thank you in advance.
using System;
using System.IO;
class Test
{
static void Main(string[] args)
{
Console.WriteLine("Please :");
string hely = Console.ReadLine();
string[] __file = Directory.GetFiles(hely);
string[] __dir = Directory.GetDirectories(hely);
foreach (string i in __file)
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
foreach (string i in __dir)
{
DirectoryInfo _file = new DirectoryInfo(i);
Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
}
Console.ReadKey();
}
}
You should check existence of a path with
System.IO.Directory.Exists(directory)
and of a file with
System.IO.File.Exists(filePath)
Then, you need to take the try-catch block inside the for-loop, to catch any possible exceptions that occur because of insufficient rights/permissions.
e.g.
foreach (string i in __file)
{
try
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
throw;
}
}
You could also create two try-catch blocks - depends on what you want to do.
try
{
foreach (string i in __file)
{
try
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
throw;
}
}
}
catch (System.Exception exLoop)
{
System.Console.WriteLine(exLoop.Message);
throw;
}
Note that in your example, you should first check if the directory "hely" exists:
if (!System.IO.Directory.Exists(hely))
{
System.Console.Error.WriteLine("Directory \"{0}\" does not exist.", hely);
System.Environment.Exit(1);
// or: return;
}
Since exception handling is usually very slow, I would however recommend that you check for the existence of the file/directory explicitly. It would also be a good idea to do so for the file/directory-listing & read-access rights for the respective user. But even if you do so, keep the try-catch, because there might be cases where your program suddenly fails - e.g. when a removable storage is forcefully removed.
Use try catch
using System;
using System.IO;
class Test
{
static void Main(string[] args)
{
Console.WriteLine("Please :");
string hely = Console.ReadLine();
try
{
string[] __file = Directory.GetFiles(hely);
string[] __dir = Directory.GetDirectories(hely);
foreach (string i in __file)
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
foreach (string i in __dir)
{
DirectoryInfo _file = new DirectoryInfo(i);
Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
}
}
catch(System.IO.DirectoryNotFoundException ex)
{
Console.WriteLine("Directory not found");
}
Console.ReadKey();
}
}
You can check if the file exists
foreach (string i in __file)
{
if (File.Exists(i))
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
}
RTFM?
Read Directory.GetFiles method
It says that you will get the DirectoryNotfound exception if the specified path is not found. Obviously folder 'C:\Temp\first_project\first_project\bin\Debug\12345' does not exist.
Proper code would be:
string hely = ...
try
{
string[] files = Directory.GetFiles(hely);
ProcessFiles(files);
}
catch (DirectoryNotFoundException exc)
{
Console.WriteLine(exc.Message);
}
If you don't know how to react on exceptions read MSDN about exception handling

Moving files from one location to another

I'm trying to make this program that will move (cut and paste) all files from one directory (a folder) to another directory. In this example, I'm trying to move all the files that are inside the D:\Source folder (has a few files in it) to C:\Source folder (which has no files in it). When I run the program, I get this error.
http://s13.postimg.org/kuufg0gmu/error.jpg
Here is the full source code:
using System.IO;
namespace FileManager
{
public partial class Form1 : Form
{
string sourceDirectory = "";
//string destinationDirectory = #"C:\Destination";
string date = "";
string[] filePaths;
string destinationPath;
public Form1()
{
InitializeComponent();
}
private void buttonClean_Click(object sender, EventArgs e)
{
// Get source directory
sourceDirectory = textBoxDirectory.Text;
// Get date of files
date = textBoxDate.Text;
// Get file paths
if (Directory.Exists(sourceDirectory))
{
filePaths = Directory.GetFiles(#sourceDirectory, "*", SearchOption.AllDirectories);
foreach (string sourcePath in filePaths)
{
destinationPath = sourcePath.Remove(0, 1).Insert(0, "C");
File.Copy(sourcePath, destinationPath);
//MessageBox.Show(destinationPath);
}
}
else
{
MessageBox.Show("Directory does not exist.");
}
}
}
}
You need to check if destination directory exists than copy files otherwise first create destination directory.
foreach (string sourcePath in filePaths)
{
destinationPath = sourcePath.Remove(0, 1).Insert(0, "C");
if(!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationpath);
File.Copy(sourcePath, destinationPath);
//MessageBox.Show(destinationPath);
}
Exception clearly states that destinationPath is not valid. Make sure destinationPath exist as shown by #Mairaj then use File.Move to cut-paste. Complete code to move one file. You can your logic of directories to move all the files.
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Find more info here

My C# multi-threaded console application seems to not be multithreaded

Here's my C# console program that uses Powerpoint to convert ppt files to folders of pngs. This is supposed to be an automated process that runs on its own server.
I expect that as soon as a thread creates an image from a file, it should immediately remove the images and the source file.
The actual behavior is that, if five threads are running, it'll wait for five folders of images to be created before any thread can move any files. I'm able to see the images being created, and compare that with the Console readout, so I can see that a thread isn't trying to move the file.
Only after all the other threads have made their images, will any thread try to move the files. I suspect this is wrong.
This is an Amazon EC2 Medium instance, and it appears to max out the CPU, so five threads might be too much for this.
I also find that I can hardly use Windows Explorer while this program is running.
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;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static int currThreads = 0;
static void Main(string[] args)
{
var inDir = args[0];
var outDir = args[1]+"\\";
var procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
Thread[] converterThreads = new Thread[threadLimit];
while (true)
{
System.Threading.Thread.Sleep(1000);
var filePaths = Directory.GetFiles(inDir, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".pptx") && !s.Contains("~$") || s.EndsWith(".ppt") && !s.Contains("~$"));
var arrPaths = filePaths.ToArray();
for(var i=0; i< arrPaths.Length; i++)
{
if (currThreads < threadLimit && currThreads < arrPaths.Length)
{
Console.WriteLine("currThreads= " + currThreads + " paths found= " + arrPaths.Length);
try
{
var fileNameWithoutExtension = arrPaths[currThreads].Replace(inDir, "").Replace(".pptx", "").Replace(".ppt", "").Replace("\\", "");
var filenameWithExtension = arrPaths[currThreads].Substring(arrPaths[currThreads].LastIndexOf("\\") + 1);
var dir = arrPaths[currThreads].Replace(".pptx", "").Replace(".ppt", "");
Conversion con = new Conversion(arrPaths[currThreads], dir, outDir, procDir, filenameWithExtension, fileNameWithoutExtension);
converterThreads[i] = new Thread(new ThreadStart(con.convertPpt));
converterThreads[i].Start();
Console.WriteLine(converterThreads[i].ManagedThreadId + " is converting " + fileNameWithoutExtension);
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to convert {0} ", arrPaths[i]) + e);
}
}
}
for (var i = 0; i < converterThreads.Length; i++)
{
if (converterThreads[i] != null)
{
if (!converterThreads[i].IsAlive)
{
converterThreads[i].Abort();
converterThreads[i].Join(1);
Console.WriteLine("thread " + converterThreads[i].ManagedThreadId + " finished, "+currThreads+" remaining");
converterThreads[i] = null;
}
}
}
if (currThreads == 0)
{
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
class Conversion{
static int numberOfThreads=0;
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
int elapsedTime;
System.Timers.Timer time;
public Conversion(String input, String output, String outDir, String processDir, String nameWith, String nameWithout)
{
this.input = input;
this.output = output;
this.outDir = outDir;
process = processDir;
this.nameWith = nameWith;
this.nameWithout = nameWithout;
numberOfThreads++;
Console.WriteLine("number of threads running: " + numberOfThreads);
Program.currThreads = numberOfThreads;
time = new System.Timers.Timer(1000);
time.Start();
time.Elapsed += new ElapsedEventHandler(OnTimedEvent);
elapsedTime = 0;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
elapsedTime++;
}
public void convertPpt()
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
try
{
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);
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed");
}
moveFile();
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()
{
Console.WriteLine("moving dir " + output);
try
{
System.Threading.Thread.Sleep(500);
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)
{
}
}
finally
{
numberOfThreads--;
Program.currThreads = numberOfThreads;
Console.WriteLine("took " + elapsedTime + "seconds");
}
}
}
}
Every 1000ms you get a list of files in inDir and potentially start a thread to process each file. You have very complex logic surrounding whether or not to start a new thread, and how to manage the lifetime of the thread.
The logic is too complex for me to spot the error without debugging the code. However, I would propose an alternative.
Have a single thread watch for new files and place the file path into a BlockingCollection of files for processing. That thread does nothing else.
Have N additional threads that retrieve file paths from the BlockingCollection and process them.
This is known as a Producer / Consumer pattern and is ideal for what you are doing.
The example code at the bottom of the linked MSDN page shows an implementation example.
On a side note, you are catching and swallowing Exception e3. Don't catch something you will not handle, it hides problems.

deleting entire folder including all the files inside

The following is what i have when i try to delete a folder:
namespace sortfolder
{
class Program
{
static string path = "C:\\Work\\6.70_Extensions\\NightlyBuild\\";
static void Main(string[] args)
{
var di = new DirectoryInfo("C:\\Work\\6.70_Extensions\\NightlyBuild");
foreach (var file in di.GetFiles("*", SearchOption.AllDirectories))
file.Attributes &= ~FileAttributes.ReadOnly;
var files = Directory.GetDirectories(path, "SASE Lab Tools.*");
foreach(var file in files)
Console.WriteLine(file);
foreach(var file in files.OrderByDescending(x=>x).Skip(7))
Console.WriteLine(file);
foreach(var file in files.OrderByDescending(x=>x).Skip(7))
Directory.Delete(file);
}
}
}
As mentioned in the title, i would like to delete this folder along with all its content. How do i go about doing it? Apparently i have IOException # Directory.Delete(file) as it contains files
You missing true Directory.Delete(file,true);
For example
public static void Main()
{
string path = #"c:\MyDir\temp";
try
{
Directory.Delete(path, true);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
Directory.Delete has a second parameter which takes a bool = recrusive. Use that overload instead.
http://msdn.microsoft.com/en-us/library/fxeahc5f.aspx

Categories