C# How to get current Powerpoint Presentation File Name? - c#

As you see I have some object in my hand but I couldn't figure out how to get current file name. I am getting _currentSlideName from an xml file and compare to open new slide.
Do you have any suggestion to get current power point presentation file name?
ppt.Application _pptApplication = new ppt.Application();
private void Open(string fileName)
{
_presentation = _pptApplication.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
}
private void CheckSlide()
{
if (_oSlideShowView == null)
{
try
{
Open( _settingObj.Path + _currentSlideName);
}
catch (Exception)
{
Open(_settingObj.Path+ "Test.pptx" );
}
}
else if (_currentSlideName != _presentation.Path)
{
try
{
Open( _settingObj.Path + _currentSlideName);
}
catch (Exception)
{
Open(_settingObj.Path+ "Test.pptx" );
}
}
}

Getting the full filename of the open presentation is simply Presentation.FullName. In your case, this would be:
_pptApplication.ActivePresentation.FullName
Note that this only returns the presentation's name if the file is not currently saved. If it is not saved, the presentation's Path is an empty string.
EDIT: The example above returns the full filename. If you want only the name, use the following. Just to clarify that this only makes sense with saved presentations, I've added a check on Path.
if(!_pptApplication.ActivePresentation.Path.Equals("")) {
var name = _pptApplication.ActivePresentation.Name
... do processing...
}
else {
... error ...
}

Related

C# access to the path is denied...(System.UnauthorizedAccessException: Access to the path 'C:\' is denied.)

I have a problem with my c# program.
When I try to create a file, the program throws a exception:
the acces to the path is denied (System.UnauthorizedAccessException: Access to the path 'C:' is denied.
This is the code who create the file:
static void crate()
{
try
{
Console.WriteLine("Specify the path where the file will be created");
string pathc = Console.ReadLine();//ask the path
if (pathc != "stop")
{
Console.WriteLine("Now specify the file name ");
string wathc = Console.ReadLine();//ask the file name for the new file
if (wathc != "stop")
{
if (Directory.Exists(pathc))//check if the path exist
{
Console.WriteLine("SPECIFY THE CONTENT OF FILE!");
string modify = Console.ReadLine();//the content of the file
if(modify != "stop")
{
File.WriteAllText(pathc,modify);/here there is a exception
Console.WriteLine("DONE!");
File.Move(pathc, wathc);
beggining();
}
else
{
beggining();
}
}
else
{
Console.WriteLine("The specified path doesn't exist\n");
beggining();
}
}
else
{
beggining();
}
}
else
{
beggining();
}
}
catch (Exception e)
{
Console.WriteLine("NO! the file maybe exist....retry please ex:C:/p.txt ({0})\n", e.GetBaseException());
beggining();
}
}
Try to work with the file ะก:\Test\p.txt or D:\Test\p.txt
In the line File.WriteAllText(pathc,modify); you try to write to the definite file, but it looks like var pathc was initialized with path only (e.g. E:\).
I would suggest using
wathc = Path.Combine(pathc, wathc);
File.WriteAllText(wathc, modify);
Console.WriteLine("DONE!");
beggining();
the line File.Move(pathc, wathc); should be removed because you already have the file with right filename and needed context.
Normally C drive's access is denied.
If you want to still access the C: Drive then change the ownership to everyone by seeing this reference.
https://www.techrepublic.com/article/how-to-change-ownership-of-files-and-folders-in-windows-10/

C# checking if more files have one of more of these strings

it's me again , your boi...
Stuck with another problem I didn't find anywhere else strangely...
This is the code I possess in order to check if files in a directory and subdirectiories have a certain string. If they do, I'll add a string at the bottom of the file...
I followed for most part the documentation on Microsoft Docs.
public class OFiles
{
public string PathProgetto
{
get;
set;
}
public void Change()
{
try
{
string docPath = PathProject;
var files = from file in Directory.EnumerateFiles(docPath, "*.h", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains("String I want")
// where line.Contains("Other String I want")
// where line.Contains("Another String I want")
select new
{
File = file,
Line = line
};
System.Collections.ArrayList arr = new System.Collections.ArrayList();
foreach (var f in files)
{
arr.Add(f.File.ToString());
}
string sNuovaRiga = "This One";
foreach (var s in arr)
{
File.AppendAllText(s.ToString(), "\r\n" + sNuovaRiga);
}
Console.WriteLine($"{files.Count().ToString()} files found and modified.");
}
catch (UnauthorizedAccessException uAEx)
{
Console.WriteLine(uAEx.Message);
}
catch (PathTooLongException pathEx)
{
Console.WriteLine(pathEx.Message);
}
}
}
You'll notice that there are other strings I want my program to check. The problem is that I have no idea how to do it, I only know that the way I did it I cannot do it with another WHERE so I'm asking here. Ask me anything unclear and thanks in advance
I want to close this question, so I'll just answer it.
As #elgonzo suggested, in this particular all I had to do was putting || when I had to choose between the strings.

Creating different XML files depending on the existence of others c#

having an issue when saving data, I am trying to set it up so if the user tries to save their name data for their character and a file already exists, it will create a second xml file "NameData2.xml" and so forth until a maximum of 3 files is reached, ( so the user has differant characters to choose from ) however at the moment it is simply creating 2 xml files at once all containing the same name ( i would guess this is due to them checking all at once in the same if else statements possibly? all i could find when trying to find an answer was how to check for a files existence and if it cant find it how to create one, i will post my code below if anyone has any suggestions that would be brilliant as im quite stumped!
Thankyou in advance.
// This will save the users generated name in a created file
// NameData.xml and will take the user to the partySelectionScreen.
private void continueButton_Click(object sender, RoutedEventArgs e)
{
try
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, "NameData.xml");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if(File.Exists("NameData.xml"))
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, "NameData2.xml");
}
else if (File.Exists("NameData2.xml"))
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, "NameData3.xml");
}
else if (File.Exists("NameData3.xml"))
{
MessageBox.Show("You have passed the limit of existing characters" +
"To continue please return to the main menu and delete at least 1 character");
}
You should do like this.
This will perform a a search on the files that doesn't exists and will generate them. This will permit the user to delete any character the wants without breaking the algorithm.
private void continueButton_Click(object sender, RoutedEventArgs e)
{
if(!File.Exists("NameData.xml"))
{
SaveFileInfo("NameData.xml");
}
else if (!File.Exists("NameData2.xml"))
{
SaveFileInfo("NameData2.xml");
}
else if (!File.Exists("NameData3.xml"))
{
SaveFileInfo("NameData3.xml");
}
else
{
MessageBox.Show("You have passed the limit of existing characters" +
"To continue please return to the main menu and delete at least 1 character");
}
}
public SaveFileInfo(string fileName)
{
try
{
NameSavingInformation nameInfo = new NameSavingInformation();
nameInfo.GeneratedName = generatedNameTexbox.Text;
SaveXml.SaveData(nameInfo, fileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Cannot create a file when that file already exists when using Directory.Move

I am trying to move the directory from one location to another location on the same drive. I am getting "Cannot create a file when that file already exists" error. Below is my code.
could any one suggest on this?
string sourcedirectory = #"F:\source";
string destinationdirectory = #"F:\destination";
try
{
if (Directory.Exists(sourcedirectory))
{
if (Directory.Exists(destinationdirectory))
{
Directory.Move(sourcedirectory, destinationdirectory);
}
else
{
Directory.CreateDirectory(destinationdirectory);
Directory.Move(sourcedirectory, destinationdirectory);
}
}
}
catch (Exception ex)
{
log(ex.message);
}
As both of the previous answers pointed out, the destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
Something like this:
class Program
{
static void Main(string[] args)
{
string sourcedirectory = #"C:\source";
string destinationdirectory = #"C:\destination";
string backupdirectory = #"C:\Backup";
try
{
if (Directory.Exists(sourcedirectory))
{
if (Directory.Exists(destinationdirectory))
{
//Directory.Delete(destinationdirectory);
Directory.Move(destinationdirectory, backupdirectory + DateTime.Now.ToString("_MMMdd_yyyy_HHmmss"));
Directory.Move(sourcedirectory, destinationdirectory);
}
else
{
Directory.Move(sourcedirectory, destinationdirectory);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
from http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx
"This method throws an IOException if, for example, you try to move c:\mydir to c:\public, and c:\public already exists. You must specify "c:\public\mydir" as the destDirName parameter, provided that "mydir" does not exist under "c:\public", or specify a new directory name such as "c:\newdir"."
You don't need to create Directory first, it will throw IO Exception, if destination directory exists, Move method automatically creates it for you:
string sourcedirectory = #"F:\source";
string destinationdirectory = #"F:\destination";
if (Directory.Exists(sourcedirectory))
{
if (!Directory.Exists(destinationdirectory))
{
Directory.Move(sourcedirectory, destinationdirectory);
}
}
More infomation of Directory.Move:
http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx
As per MSDN,
This method throws an IOException if, for example, you try to move
c:\mydir to c:\public, and c:\public already exists.
But, in your method, you are creating the destination directory before you move.
So, you need to change your method from
if (Directory.Exists(destinationdirectory))
{
Directory.Move(sourcedirectory, destinationdirectory);
}
else
{
Directory.CreateDirectory(destinationdirectory);
Directory.Move(sourcedirectory, destinationdirectory);
}
to
if (Directory.Exists(destinationdirectory))
{
//delete or rename
}
Directory.Move(sourcedirectory, destinationdirectory);
You can just call
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(source, destination, true);
What it does internally is it creates the target directory if it's not exists and then it iterates over the source directory's files and moves them to the target directory. That way the problem of "Cannot create a file when that file already exists" won't happen.
You'll need to add Microsoft.VisualBasic as a reference.

File operations

I wanted move the file from one folder to another(target) folder.If the same file is already exist in target folder i wants to rename .how to implement in C#.
Thanks in advance
Sekar
System.IO.File.* has everything you need.
System.IO.File.Exists = To check if the file exists.
System.IO.File.Move = To move (or rename a file).
Fundamentally, this is:
string source = ..., dest = ...; // the full paths
if(File.Exists(dest))
{
File.Move(dest, Path.GetTempFileName());
}
File.Move(source, dest);
You'll want to use the System.IO.File class and check for the file's existence ahead of time.
if(File.Exists("myfile.txt"))
File.Move("myfile.txt", "myfile.bak");
File.Move("myotherfile.txt","myfile.txt");
If you prefer a windows-style behavior, so there is the code I'm using for such an operation
public static void FileMove(string src,ref string dest,bool overwrite)
{
if (!File.Exists(src))
throw new ArgumentException("src");
File.SetAttributes(src,FileAttributes.Normal);
string destinationDir = Path.GetDirectoryName(dest);
if (!Directory.Exists(destinationDir))
{
Directory.CreateDirectory(destinationDir);
}
try
{
File.Move(src,dest);
}
catch (IOException)
{
//error # 183 - file already exists
if (Marshal.GetLastWin32Error() != 183)
throw;
if (overwrite)
{
File.SetAttributes(dest,FileAttributes.Normal);
File.Delete(dest);
File.Move(src,dest);
}
else
{
string name = Path.GetFileNameWithoutExtension(dest);
string ext = Path.GetExtension(dest);
int i = 0;
do
{
dest = Path.Combine(destinationDir,name
+ ((int)i++).ToString("_Copy(#);_Copy(#);_Copy")
+ ext);
}
while (File.Exists(dest));
File.Move(src,dest);
}
}
}

Categories

Resources