Command to copy a file to another, user-chosen directory? - c#

I have this code to copy a file to another destination, however I need the users to choose the destination plus the name of file copied is = the old name with the date and hour of my PC ..
string fileToCopy = #"d:\pst\2015.pst";
string destinationDirectoryTemplate = textBox2.Text;
var dirPath = String.Format(destinationDirectoryTemplate, DateTime.UtcNow);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
{
di.Create();
}
var fileName = Path.GetFileName(fileToCopy);
var targetFilePath = Path.Combine(dirPath, fileName);
File.Copy(fileToCopy, targetFilePath);

This should work
protected void Button3_Click(object sender, EventArgs e)
{
string fileToCopy = #"e:\TestFile.pdf";
string destinationDirectoryTemplate = TextBox1.Text;
var dirPath = string.Format(destinationDirectoryTemplate, DateTime.UtcNow);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
{ di.Create(); }
var fileName = Path.GetFileNameWithoutExtension(fileToCopy);
var extn = Path.GetExtension(fileToCopy);
var finalname = fileName + " " + string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + extn;
var targetFilePath = Path.Combine(dirPath, finalname);
File.Copy(fileToCopy, targetFilePath);
}

Related

Decompress a .s file in c# windows form application

I am trying to decompress a .s file programmatically using c#. I have tried using all the possible methods I know but couldn't decompress it. My actual file would be a file.tar.gz, I have uncompressed .tar.gz using ICSharpCode.SharpZipLib.Tar and ICSharpCode.SharpZipLib.GZip. In my uncompressed folder I would be having different files with "file_1.s" format. Can someone guide me plz?
Here is my function for decompressing:
public void ExtractTGZ(String gzArchiveName, String destFolder)
{
Stream inStream = File.OpenRead(gzArchiveName);
Stream gzipStream = new GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
}
public void ExtractTar(String tarFileName, String destFolder)
{
Stream inStream = File.OpenRead(tarFileName);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
inStream.Close();
}
When a button event Occurs it will select the file.tar.gz from windows explorer and with next button it will start decompressing and its code is as shown below:
private void OpenFileLocationEvent(object sender, EventArgs e)
{
if (openLogs.ShowDialog() == DialogResult.OK)
{
tbTargetFile.Text = openLogs.FileName;
}
}
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
//MessageBox.Show("Source File:" + tbTargetFile.Text + " ExtrctdDirectory:" + nextDirectory);
_uc.ExtractTGZ(tbTargetFile.Text, nextDirectory);//Extract .tar.gz
string[] files = Directory.GetFiles(nextDirectory, "*.s");
string filename = "";
string targetFile = "";
string newFile = "";
int count = 0;
foreach (string f in files)
{//Changing File Type
filename = Path.GetFileName(f);
targetFile = nextDirectory + "//" + filename;
newFile = nextDirectory + "//File_" + count + ".tar";
File.Move(targetFile, newFile);
count += 1;
//FileInfo finfo = new FileInfo(targetFile);
//finfo.MoveTo(Path.ChangeExtension(targetFile, ".txt"));
}
string[] tarfiles = Directory.GetFiles(nextDirectory, "*.tar");
foreach (string f in tarfiles)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
MessageBox.Show("Traget File:" + targetFile + " ExtrctdDirectory:" + extrctdDirectory);
_uc.ExtractTar(targetFile, extrctdDirectory);
//_uc.ExtractTarByEntry(targetFile, extrctdDirectory, false);
//ZipFile.ExtractToDirectory(targetFile, extrctdDirectory);
}
}
}
Using a 7zip console application solved my problem. And this is my code.
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "7za.exe";
p.Arguments = "x \"" + tbTargetFile.Text + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
string[] files = Directory.GetFiles(nextDirectory, "*.tar");
string filename = "";
string targetFile = "";
foreach (string f in files)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
}
p.Arguments = "x \"" + targetFile + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
targetFile = nextDirectory + "\\*.s";
p.Arguments = "x \"" + targetFile + "\" -o\"" + extrctdDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
}
}

Creating Folders dynamically using CSOM in sharepoint causes ID issues for the document

I am creating the nested folders dynamically for a document library and uploading files. The below code is working fine. but the issues is whenever i uploading the file to the existence folder the ID of the document for the uploaded documents is not in sequence. Suppose if i am uploading a file to path projects\PRJ1\Assignment, fist time it was creating the folders and file with ID's(1\2\3\4) respectively . If i upload other document to the same folder the id of the folders is not changing but the id of the file is 8. i am not unable to find the id 5,6,7 in the document library.
using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
clientContext.Credentials = new System.Net.NetworkCredential(Username, Password, Domain);
CSOM.Web _Site = clientContext.Web;
// string listrootfolder = "Testlist";
CSOM.List _List = _Site.Lists.GetByTitle("Testlist");
clientContext.Load(_List.RootFolder);
clientContext.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
var folder = CreateFolder(clientContext.Web, "Testlist", folderpath);
// uploading the document
CSOM.FileCreationInformation newFile = new CSOM.FileCreationInformation();
// newFile.Content = System.IO.File.ReadAllBytes(#"D:\Testupload.docx");
byte[] bytes = Convert.FromBase64String(objReqDocumentDetials.FileData.ToString());
newFile.Content = bytes;
// newFile.Url = objDocumentDetials.AttachmentName.ToString() + DateTime.Now.ToString("ddMMyyyyHHmmsss") + "." + objDocumentDetials.FileType.ToString();
newFile.Url = objReqDocumentDetials.FileName.ToString() + "." + objReqDocumentDetials.FileType.ToString();
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File _UploadingFile = folder.Files.Add(newFile);
var item = _UploadingFile.ListItemAllFields;
// var folder = item.GetFolder("account/" + folderName);
// item["Year"] = DateTime.Now.Year.ToString();
// item.Update();
clientContext.Load(_UploadingFile, f => f.ListItemAllFields);
clientContext.ExecuteQuery();
}
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
throw new ArgumentNullException("fullFolderPath");
CSOM.List list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);
}
public CSOM.Folder CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
The issue was fixed after redefined the CreateFolder and CreateFolderInternal methods as below
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
CSOM.List _List = web.Lists.GetByTitle(listTitle);
web.Context.Load(_List.RootFolder);
web.Context.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
string root = "";
for (int i = 0; i < folderUrls.Length; i++)
{
root = folderUrls[i].ToString();
string targetFolderUrl = "/" + listrootfolder + "/" + string.Join("/", folderUrls, 0, i + 1);
var folder1 = web.GetFolderByServerRelativeUrl(targetFolderUrl);
web.Context.Load(folder1);
bool exists = false;
try
{
web.Context.ExecuteQuery();
exists = true;
}
catch (Exception ex)
{
}
if (!exists)
{
if (i == 0)
{
CreateFolderInternal(web, _List.RootFolder, root);
}
else
{
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
var targetfolderUrls = targetFolderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string jj = string.Join("/", targetfolderUrls, 0, targetfolderUrls.Length - 1);
CSOM.Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + jj);
web.Context.Load(folder);
web.Context.ExecuteQuery();
SPCreateFolderInternal(web, folder, root);
}
}
else
{
//already folder exists
}
}
CSOM.Folder finalfolder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + listrootfolder + "/" + fullFolderPath);
web.Context.Load(finalfolder);
web.Context.ExecuteQuery();
return finalfolder;
}
private void CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
try
{
var curFolder = parentFolder.Folders.Add(fullFolderPath);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
}
catch (System.Exception ex)
{
}
}

The process cannot access the file because it is being used by another process error while moving image

I've a folder named testPhotos with some images. Based on the image creation date, I want to create a new folder by image creation year and then move the image to that folder.
For example, testPhotos has image named 01.jpg which was created on 2011. So I want to create a folder named 2011 inside testPhotos like testPhotos\2011 and move image to that folder. While doing this I am getting The process cannot access the file because it is being used by another process. error while moving image from one folder to another.
Code:
private void button1_Click(object sender, EventArgs e)
{
var creationDate = new DateTime();
var dateList = new List<String>();
var fileName = String.Empty;
var sourceFolder = #"C:\My Stuff\Test Porjects\testPhotos";
String[] images = Directory.GetFiles(sourceFolder);
if (images.Count() > 0)
{
foreach (var imagePath in images)
{
fileName = Path.GetFileName(imagePath);
creationDate = GetDateTakenFromImage(imagePath);
var date = creationDate.GetDateTimeFormats()[5].Replace("-", "/");
if (!String.IsNullOrEmpty(date))
{
var year = date.Substring(0, 4);
var destinationFolder = sourceFolder + "\\" + year;
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
String fileToMove = sourceFolder+ "\\" + fileName;
String moveTo = destinationFolder + "\\" + fileName;
File.Move(fileToMove, moveTo);
}
}
}
}
}
private DateTime GetDateTakenFromImage(string path)
{
Image myImage = Image.FromFile(path);
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = new Regex(":").Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
Any ideas?
This looks like a missing dispose on the image, try with the following:
private DateTime GetDateTakenFromImage(string path)
{
using (Image myImage = Image.FromFile(path))
{
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = new Regex(":").Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
}

C# str.Replace only replaces first character

This is my code, I know it isn't optimal, but it works for me.
private void textBox_title1_TextChanged(object sender, EventArgs e)
{
string title1 = textBox_title1.Text;
string currentDirectory = Directory.GetCurrentDirectory();
DateTime folderDate = DateTime.Today;
string workingFolder = folderDate.ToString("ddMMMyy");
string mailingDir = ("mailingdir\\");
string indexPage = (mailingDir + "\\" + workingFolder + "\\" + "index.html");
String appdir = Path.GetDirectoryName(Application.ExecutablePath);
String title1open = Path.Combine(appdir, mailingDir, workingFolder, "index.html");
string str = File.ReadAllText(title1open, Encoding.UTF8);
str = str.Replace("[title1]", title1);
File.WriteAllText(title1open, str);
}
However, this only saves the first character that is entered into textBox_title1

Convert from a DataUrl to an Image in C# and write a file with the bytes

Hello I have signature like this:
which is encoded to a DataUrl specifically this string:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs... (long string)"
What i want to do is Convert this DataUrl to an PNG Image, and save the image to the device, this is what i am doing so far:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(path, base64Data);
if (!File.Exists(filename))
{
using (var stream = new MemoryStream(binData))
{
//Code crashing here--------------------------
File.WriteAllBytes(filename, binData);
}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
But my code is making my application to crash specifically in this line:
File.WriteAllBytes(filename, binData);
The sample I am using as reference (Link) is using a PictureBox but with Xamarin there is no use of a pictureBox.
Any Ideas?
As #SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename for further help this is the working code:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//filename = Path.Combine(path, base64Data.Replace(#"/", string.Empty));
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
string fileName = "Sn" + milliseconds.ToString() + ".PNG";
filename = Path.Combine(path, fileName);
if (!File.Exists(filename))
{
//using (var stream = new MemoryStream(binData))
//{
File.WriteAllBytes(filename, binData);
//}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
And the image showed:
I just cleaned Mario's code and fine tuned regex:
public string SaveDataUrlToFile(string dataUrl, string savePath)
{
var matchGroups = Regex.Match(dataUrl, #"^data:((?<type>[\w\/]+))?;base64,(?<data>.+)$").Groups;
var base64Data = matchGroups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
System.IO.File.WriteAllBytes(savePath, binData);
return savePath;
}

Categories