How to remove folder path in zip file - asp.net

I am generating the zip file from this folder "D:\Nagaraj\Dotnet\Zipfile\Zipfile\Filebuild\Hi" within that "Hi" folder has 2 txt files. .....yes Now generating the Hi.zip file.But problem is Within that zip file has this particular path "D:\Nagaraj\Dotnet\Zipfile\Zipfile\Filebuild\Hi" and within that hi folder has 2 txt fils. Now I need to remove this path "D:\Nagaraj\Dotnet\Zipfile\Zipfile\Filebuild\Hi" and directly generate that Hi.zip file and within that 2 txt file......thanks ....in advance
I am using sharpziplib library enter code here
protected void Page_Load(object sender, EventArgs e)
{
StartZip("D:/Nagaraj/Dotnet/Zipfile/Zipfile/Filebuild/Hi",".zip");
}
public void StartZip(string directory, string zipFileName)
{
ZipFile z = ZipFile.Create(directory + zipFileName);
z.BeginUpdate();
string[] filenames = Directory.GetFiles(directory);
foreach (string filename in filenames)
{
z.Add(filename);
}
z.CommitUpdate();
z.Close();
}

From the help file, where you add your files, you say how to do you like to show inside the zip.
public void StartZip(string directory, string zipFileName)
{
using(ZipFile z = ZipFile.Create(directory + zipFileName))
{
z.BeginUpdate();
// Create a reference to the directory.
DirectoryInfo di = new DirectoryInfo(directory);
// Create an array representing the files in the current directory.
FileInfo[] fi = di.GetFiles();
// here the entryName is the name that you like to show inside zip
foreach (FileInfo fiTemp in fi)
z.Add(fiTemp.FullName, fiTemp.Name);
z.CommitUpdate();
z.Close();
}
}

Related

How to avoid extent report to not to overwrite the html file name

I am using extent reports in appium with testng and its working fine for me.whenver my tests run is completed then extent report generates html file in my project folder and that is what expected.
Issue is that when I again run my tests then extent report generate new html report file by overwrting the name of previously created html file.
I want extent report to generate html file with unique names or name with date in in, each time when I run my tests
You can create your file name to be the current timestamp. This way, it will be easy to have a unique name for your report file -
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
extent = new ExtentReports (userDir +"\\test-output\\" + timeStamp + ".html", true);
You can do it by setting unique name:
String reportFile = resultDirectory + fileName + ".html";
than method for saving report to certain folder:
public void saveReportFolder() throws IOException {
File srcDir = new
File(System.getProperty("user.home")+"/Automation/target");
File destDir = new File(System.getProperty("user.home") + "/reports/"+ System.getProperty("user.name")+"/"+dateTimeGenerator());
FileUtils.copyDirectory(srcDir, destDir);
}
...and utility for setting dateTime:
public static String dateTimeGenerate(){
Format formatter = new SimpleDateFormat("YYYYMMdd_HHmmssSSS");
Date date = new Date(System.currentTimeMillis());
return formatter.format(date);
}
Or simply use klov reports start server and have everything in database (MongoDb), it is more elegant way to go.
Hope this helps,
I use:
private static String timestamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()).replaceAll(":", "-");
public static String reportFullPath = getReportsPath() + "\\AutomationReport_" + timestamp + ".html";
I have done it like this, simple and crisp.
String Outputfilename= ExecutionConfig.FileOutname;
System.err.close(); // written to remove JAVA 9 incompatibility.. continued below
System.setErr(System.out); // continue.. and remove the warnings
extent = new ExtentReports(System.getProperty("user.dir") + "/test-output/"+Outputfilename+".html", true);
So here ExecutionConfig.FileOutname is called from the class ExecutionConfig where i am reading the values from the config.properties file. and then here assigning it to the output-file.
Also it worked for me.
I also faced a similar issue. As in the real-world, we need old reports as well. Below is the solution in Java for Extent PDF report
I added an event listener method. Event used- TestRunStarted. We further need to register for this event too. The solution can be done for HTML report too.
public void setCustomReportName(TestRunStarted event)
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String currenttimestamp =sdf.format(timestamp);
Properties prop=new Properties();
//extent.reporter.pdf.out is the name of property which tell the report path
prop.setProperty("extent.reporter.pdf.out", "test output/PdfReport/ExtentPdf_"+currenttimestamp+".pdf");
ExtentService e1 =new ExtentService();
//ExtentReportsLoader is the inner class of ExtentService and initPdf is its private method which takes the path for report
Class<?>[] a=e1.getClass().getDeclaredClasses();
Method met;
//Even there is exception test run wont fail and report will also be generated (ExtentPdf.pdf)
try {
met = a[0].getDeclaredMethod("initPdf", Properties.class);
met.setAccessible(true);
met.invoke(a[0], prop);
} catch (NoSuchMethodException e) {
System.out.println("There is no method with name initPdf");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
System.out.println("Argument passed to method initPdf are not correct");
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}

Directory.GetDirectories doesn't work as I thought

public Dir(string rootDir)
{
Directories = new List<string>();
RootDir = rootDir;
foreach(string dir in Directory.GetDirectories(RootDir, #"*.mp3", SearchOption.AllDirectories))
{
Directories.Add(dir);
Debug.Print(dir);
}
Shuffle(Directories);
}
With this code, I wanted to find all the .mp3 files in one folder, but it came out to make a zero element in 'Directories'. What seems to be the problem?
*.mp3 are files. Use Directory.GetFiles();
If you are looking for all mp3s within folders. Do something like this (pseudo-code):
List<string> mp3s = new List<string>();
foreach(string directory in Directory.GetDirectories(_rootFolder)){
foreach(string file in Directory.GetFiles(directory)){
mp3s.Add(file);
}
}

How to load Resx Files under App_LocalResources to Iterate through it

I need the ResX file for the current page which is saved under "App_LocalResources".
I need to iterate through it.
The Method "GetLocalResourceObject" only allows access to one key at the time.
Since a resx file is nothing more than a xml file, you can loop all the elements with XElement
string resxFile = Server.MapPath("/App_LocalResources/Default.aspx.resx");
foreach (XElement element in XElement.Load(resxFile).Elements("data"))
{
string currentItem = string.Format("Key: {0} Value: {1}", element.Attribute("name").Value, element.Element("value").Value);
}
Another option is with the ResXResourceReader. However you do need to add System.Windows.Forms as a reference to the project.
using System.Resources;
//define the filename and path for the resx file
string resxFile = Server.MapPath("/App_LocalResources/Default.aspx.resx");
//load the file into the reader
using (ResXResourceReader reader = new ResXResourceReader(resxFile))
{
//loop all the entries
foreach (DictionaryEntry entry in reader)
{
string currentItem = string.Format("Key: {0} Value: {1}", entry.Key, entry.Value);
}
}

create Directory and if exist then rename it

i am developing application in which i want that if user create folder and if it is already present then folder should automatically renamed by appending number to folder name
suppose server has folder with name Time now if user again creates folder than it new folder will be Time1 again user creates folder with same name(Time or Time1) than new Folder should be created with Time2 and so on... This is what i have done so far but recursion always return wrong value.
public string checkIfExist(String path, String ProgramName, int itteration,out string strFolderName)
{
String uploadPath = "";
strFolderName = "";
String Mappath =HttpContext.Current.Server.MapPath(path);
if (Directory.Exists(Mappath))
{
String Path = HttpContext.Current.Server.MapPath((path + "" + ProgramName.Replace(" ", "_")));
// uploadPath += ++itteration ;
if (Directory.Exists(Path))
{
ProgramName += ++itteration;
strFolderName = ProgramName;
uploadPath = checkIfExist(path, ProgramName, itteration,out strFolderName);
}
}
return ProgramName;
}
Perhaps you could adapt this, to your need. I wrote it on the fly based on a piece of code I remember in an old file manager I was using in some projects, so please test it. This doesn't include creation and so on, based on your example I'm sure you can add that yourself but if you need help just comment below.
The idea is to pass the original name of the directory you want, and then return an appropriate new name if it exists, such as Test(1), Test(2), Test(n). Then once you get the name you need, you can create it directly.
protected string GetUniqueDirectoryName(string dirName)
{
string newDirName = dirName;
for (int i = 1; Directory.Exists(Server.MapPath("PATH_HERE") + newDirName); i++)
{
newDirName = string.Format("{0}({1})", dirName, i);
}
return newDirName;
}
Note: You will need to include System.IO and probably use HttpContext.Current.Server.MapPath instead of Server.MapPath
I don't know if I really understand what you are trying to do, but I think using recursion here is a little overkill. Try something like this:
string dirName = "Time";
int counter = 0;
string dir = dirName;
while(Directory.Exists(dir))
{
dir = String.Format("{0}{1}", dirName, (++counter).ToString());
}
Directory.CreateDirectory(dir);

How to extract directory (and sub directories) from jar resource?

I've a dir (with sub dirs) template that is kept as a resource inside a jar file. During run
time I need to extract it (template) to tmp dir change some content and finally publish it as a zipped artifact.
My question is: how to extract this content easily? I was trying getResource() as well as getResourceAsStream()..
Following code works fine here: (Java7)
String s = this.getClass().getResource("").getPath();
if (s.contains("jar!")) {
// we have a jar file
// format: file:/location...jar!...path-in-the-jar
// we only want to have location :)
int excl = s.lastIndexOf("!");
s = s.substring(0, excl);
s = s.substring("file:/".length());
Path workingDirPath = workingDir = Files.createTempDirectory("demo")
try (JarFile jf = new JarFile(s);){
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
String name = je.getName();
if (je.isDirectory()) {
// directory found
Path dir = workingDirPath.resolve(name);
Files.createDirectory(dir);
} else {
Path file = workingDirPath.resolve(name);
try (InputStream is = jf.getInputStream(je);) {
Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
} else {
// debug mode: no jar
}

Resources