Is Extendscript able to duplicate a file using File Object ( File. )? - adobe

Want to duplicate a file in a local directory with a new file extension. I don't see any documentation for duplicating a file with the File Object.
I see the ability to File.copy(), etc but nothing having to do with duplicating or saving without a dialog box with a new name and extension.
var targetFile = new File('myFile');
targetFile.saveDlg('newFileName' + 'extension');

To do it by code, you must be more explicit. You can try this:
function duplicateFile(path) {
var content, extension, file, fileOk, name, newFile, newPath;
file = new File(path);
if(!file) {
return
}
fileOk = file.open('r');
if(fileOk){
//Get file extension
name = file.name.split('.');
extension = name.pop();
name.join('.');
//Creating new file
//Becareful with the name, you must to check that a file with the same name doesn't exists
//if you don't want to overwrite it.
name = name + '_copy.' + extension
newPath = file.parent.fsName + '/' + name
newFile = new File(newPath);
fileOk = newFile.open('w');
//Writing content to new file
if (fileOk) {
newFile.write(content);
newFile.close(); //Remember to close the files
}
file.close()
}
}

Related

Empty file received using HTTP Post method

I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.

Trying to Create a Folder, but it creates in different location

In my ASP.NET WEbForms app, I want to create a folder and save files in it. In my project I have a folder named CRMImages/Projects. I want to create a sub folder in Projects folder & save images from their. Currently I retrieve images from CRMImages/ as the parent folder.
This is my code that I have on code-behind :
try
{
string pathToCreate = "~/CRMImages/Projects/" + item.ProjectId;
string myFileName = "";
if (!Directory.Exists(Server.MapPath(pathToCreate)))
{
DirectoryInfo di = Directory.CreateDirectory(pathToCreate);
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
System.Security.AccessControl.DirectorySecurity sec = di.GetAccessControl();
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
System.Security.AccessControl.FileSystemRights.Modify,
System.Security.AccessControl.AccessControlType.Allow));
di.SetAccessControl(sec);
Directory.CreateDirectory(pathToCreate);
System.Diagnostics.Debug.WriteLine("FOLDER CREATED PATH : " + di.FullName);
myFileName = pathToCreate + "/projectLogo.png";
System.Diagnostics.Debug.WriteLine("PATH To Save Logo File & NAME : " + myFileName);
/*
if (File.Exists(item.ProjectLogoUrl) ) {
FileUpload projLogoUpload = new FileUpload();
if (projLogoUpload.HasFile) {
myFileName = pathToCreate + "/projectLogo.png";
projLogoUpload.SaveAs(myFileName);
}
// panFileBtn.SaveAs(filePath);
} */
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("EXCEPTION While SAving File : " + ex.Message + "\n *** STACK" + ex.StackTrace);
}
The code executes, but I don't see the folder created in my project folder. Lets say the value of item.ProjectId is "EMP3", the logs that I see on the above code execution is :
FOLDER CREATED PATH : C:\Program Files (x86)\IIS Express\~\CRMImages\Projects\EMP3
PATH To Save Logo File & NAME : ~/CRMImages/Projects/EMP3/projectLogo.png
I checked in IIS Express folder & there this full path is created. Can you say why is it saving in IISExpress & how to create the folder in the /CRMImages/Projects folder that already exists in my project !!
Any help is highly appreciated.
Thanks
You have to replace below line
DirectoryInfo di = Directory.CreateDirectory(pathToCreate);
With
DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(pathToCreate));

Uploading files and preventing duplicates by knowing to update the file

In our system, when a user uploads a file it is stored in a unique file system structure and a database record is generated. A file is uploaded via the webbrowser via XMLHttpRequest. The file then gets moved from the temporary upload area into the FS.
How can I detect that a file after being uploaded already exists in my FS?
If the file uploaded is the same as one already uploaded.
If the file is the same file, but the uploaded content has been updated which
means I need to update the file in the FS.
I am ignoring file names as a way of knowing if the file already exists. A filename cannot be considered unique. An example is that some cameras name photos using an incremental number that rolls over after a time.
When a file is uploaded via the web browser, the source file structure is masked. E.g. C:\Users\Drive\File\Uploaded\From. So I cant use the that to figure out if the file has already been uploaded.
How do I know the file being uploaded already exists because its content is the same. Or it exists but because the uploaded file has been changed, so I can just update the file?
Microsoft Word documents create a challenge as Word regenerates the file on every save.
In a situation where the user renames a file on their own accord, I could say tough luck.
I would start with finding files that are the same via an SHA Hash. You could use something like this to get a list of files that have the same hash as your newly uploaded file then take some action.
Just an example of getting the hash of the new file:
string newfile;
using(FileStream fs = new FileStream( string newfile;
using(FileStream fs = new FileStream("C:\\Users\\Drive\\File\\Uploaded\\From\\newfile.txt", FileMode.Open))
{
using (System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed())
{
newfile = BitConverter.ToString(sha1.ComputeHash(fs));
}
}
This goes through all files and gets a list of file names and hashes
var allfiles = Directory.GetFiles(#"var allfiles = Directory.GetFiles(#"C:\Users\Drive\File\Uploaded\From\", "*.*")
.Select(
f => new
{
FileName = f,
FileHash = new System.Security.Cryptography.SHA1Managed()
.ComputeHash(new FileStream(f,
FileMode.Open,
FileAccess.Read))
})
.ToList();
foreach(var fi in allfiles){
if(newfile == BitConverter.ToString(fi.FileHash))
Console.WriteLine("Match!!!");
Console.WriteLine(fi.FileName + ' ' + BitConverter.ToString(fi.FileHash));
}
}", ".")
.Select(
f => new
{
FileName = f,
FileHash = new System.Security.Cryptography.SHA1Managed()
.ComputeHash(new FileStream(f,
FileMode.Open,
FileAccess.Read))
})
.ToList();
This loops through them all and looks for a match to the new one.
foreach(var fi in allfiles){
if(newfile == BitConverter.ToString(fi.FileHash))
Console.WriteLine("Match!!!");
Console.WriteLine(fi.FileName + ' ' + BitConverter.ToString(fi.FileHash));
}
Ideally you would save this hash when the file is uploaded since this is very intense to recompute.

How to update a PDF without creating a new PDF?

I am required to replace a word in an existing PDF AcroField with another word. I am using PDFStamper of iTEXTSHARP to do the same and it is working fine. But, in doing so it is required to create a new PDF and i would like the change to be reflected in the existing PDF itself. If I am setting the destination filename same as the original filename then no change is being reflected.I am new to iTextSharp , is there anything I am doing wrong? Please help.. I am providing the piece of code I am using
private void ListFieldNames(string s)
{
try
{
string pdfTemplate = #"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
string newFile = #"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
PdfReader reader = new PdfReader((string)pdfTemplate);
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create, FileAccess.ReadWrite)))
{
AcroFields form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys)
{
//Replace Address Form field with my custom data
if (fieldKey.Contains("Address"))
{
form.SetField(fieldKey, s);
}
}
stamper.FormFlattening = true;
stamper.Close();
}
}
}
As documented in my book iText in Action, you can't read a file and write to it simultaneously. Think of how Word works: you can't open a Word document and write directly to it. Word always creates a temporary file, writes the changes to it, then replaces the original file with it and then throws away the temporary file.
You can do that too:
read the original file with PdfReader,
create a temporary file for PdfStamper, and when you're done,
replace the original file with the temporary file.
Or:
read the original file into a byte[],
create PdfReader with this byte[], and
use the path to the original file for PdfStamper.
This second option is more dangerous, as you'll lose the original file if you do something that causes an exception in PdfStamper.

how to strip parent folder name and use just subdirectory names when zipping

filesToInclude list has this data:
c:/temp/folder1/data.1
c:/temp/folder1/subfolder/data.1
c:/temp/folder1/subfolder2/data.1
The following DotNetZip code stores the whole path starting with /temp/ but I like to store just /folder1/ without /temp/ prefix.
using (ZipFile zip = new ZipFile())
{
foreach (var f in filesToInclude)
{
zip.AddFile(f);
}
Just specify the directory part as the second argument. This means finding the directory from the full filename, and then stripping the leading part out.
String baseDirectory = "c:/temp/";
using (ZipFile zip = new ZipFile())
{
foreach (var f in filesToInclude)
{
String directory = Path.GetDirectoryName(f);
// Consider adding error checking here to make sure that
// directory really does start with baseDirectory!
String relative = directory.Substring(baseDirectory.Length);
zip.AddFile(f, relative);
}
}

Resources