How to insert/replace string value into another string value at certain place? - string

This is an uploading tool. I am trying to rename a file name if it is existed in the folder already.
The plan is to add a number after the file name. For example, if the file name is Hello.doc, it will be saved as Hello2.doc.
The problem is, the file name & file type are always different. It can be Goodbye.pdf/capture.png. I am not sure how to insert the number in the correct place.
if (System.IO.File.Exists(savepath))
{
int counter = 2;
while (System.IO.File.Exists(savepath))
{
string newFileName = fileName + counter;
tempFileName = newFileName.Insert/replace //Not sure what to do here
savepath += tempFileName;
counter++;
}
FileUpload.SaveAs(savepath);
lblUpload.Text = "A file with the same name already exists." + " Your file was saved as " + tempFileName;
}
Does someone know? Thanks!

Please let me know if this is what you were looking for. Used StringBuilder to avoid creating new String objects after every concatenation.
String[] filepath = filename.split(".");
// filepath[0] -> filename
// filepath[1] -> extension
StringBuilder newFilename = new StringBuilder(filepath[0]);
// add number
newFilename.append(2);
// add period
newFilename.append(".");
// add extension
newFilename.append(filepath[1]);
return newFilename.toString();

Related

Linq to Excel, get column names from CSV file

I need to get the column headers of CSV files with LINQ to Excel
I use the code specified on https://github.com/paulyoder/LinqToExcel
This works perefectly for .XLSX files but not for CSV
//Select File
var book = new LinqToExcel.ExcelQueryFactory(link + #"\" + fileName);
//Select firtworkbook
var query = (from row in book.Worksheet(0) select row).ToList();
var workSheetName = book.GetWorksheetNames();
var columnNames = (from row in book.GetColumnNames(workSheetName.FirstOrDefault()) select row).ToList();
I also tried hardcoding the sheet name and calling the CSV sheet1
var columnNames = (from row in book.GetColumnNames("Sheet1") select row).ToList();
This breaks and gives me this error:
Message = "'54733658.csv' is not a valid worksheet name in file...
I double checked it is the correct path.
I then tried:(It takes worksheet name which is the same as file name - extention)
string extension = System.IO.Path.GetExtension(fileName);
string result = fileName.Substring(0, fileName.Length - extension.Length);
var colNames = book.GetColumnNames(result, "A1:F1").ToList();
This gives me the following error:
The Microsoft Jet database engine could not find the object '02119249$A1_Z1.txt'. Make sure the object exists and that you spell its name and the path name correctly.
I googled that error those results are not applicable.
I don't have enough time to figure out why I cant read the CSV column headers
For those of you who have the same issue:
Read the first line and make a list of strings, here is my method:
public List<string> ColumnNameGenerator(string FilePath)
{
string firstLine = "";
using (StreamReader reader = new StreamReader(FilePath))
{
firstLine = reader.ReadLine() ?? "";
}
return firstLine.Split(',').ToList();
}

Scanner Mismatch Exception when reading text file

My scanner is reading from a text file with the use of a delimiter. However when I run the program the only line that gets printed out is the first line of data then I get thrown an input mismatch exception. I believe the error is that it doesn't move onto the next line. I understand how the mismatch works I am just unsure how to fix it. I have tried putting scanner.nextLine(); in as you can see in my code below.
Here is my code for the scanner :
/**
* Method for reading the data from the electricToolData.txt file.
*/
public void readElectricToolData()
{
Frame myFrame = null; // initialises frame to null
FileDialog fileBox = new FileDialog(myFrame,
"Open", FileDialog.LOAD);
fileBox.setVisible(true);
String directoryPath = fileBox.getDirectory();
String filename = fileBox.getFile();
System.out.println(filename + " " + directoryPath); // prints out name of file and directory path
try {
File dataFile = new File(filename);
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String
//if statement checks if line starts with either "//" or space.
if (lineOfText.startsWith("//") || lineOfText.isEmpty())
{
}
else // now got real data
{
Scanner scanner2 = new Scanner(lineOfText);
scanner2.useDelimiter(",");
lineOfText.trim();
System.out.println(lineOfText);
while(scanner2.hasNext())
{
//lineOfText.trim();
boolean mRechargeable = scanner.nextBoolean();
String mPower = scanner.next();
String mToolName = scanner.next();
String mItemCode = scanner.next();
int mTimesBorrowed = scanner.nextInt();
boolean mOnLoan = scanner.nextBoolean();
int mCost = scanner.nextInt();
int mWeight = scanner.nextInt();
scanner.nextLine();
ElectricTool electricTool = new ElectricTool(mToolName, mItemCode, mTimesBorrowed, mCost, mWeight, mPower);
toolsList.add(electricTool);
}
}
//System.out.println(lineOfText); // prints out string
}
scanner.close();
scanner.close(); // closes scanner
}
catch(FileNotFoundException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
The error gets shown at the boolean mRechargeable = scanner.nextBoolean();.
Here is the data file :
// this is a comment, any lines that start with //
// (and blank lines) should be ignored
// data is rechargeable, power, toolName, itemCode, timesBorrowed, onLoan, cost, weight
true,18V,Makita BHP452RFWX,RD2001,12,false,14995,1800
true,10.8V,Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
false,1350W,DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
false,1500W,Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
true,10.8V,Bosch GSR10.8-Li Drill Driver,RD3021,25,true,9995,820
false,900W,Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
true,10.8V,Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
true,18V,DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
false,2100W,Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400
The problem is that String.trim() doesn't work the way you think it does: it doesn't mutate the String it is called on, but returns a new String that effectively has the whitespace removed. This is causing the line to not be trimmed, and that "blank line" that has a lot of space characters on it then fails to be parsed with your first scanner.nextBoolean() call.
So, update:
String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String
to be:
// read the next line of the file, removing enclosing whitespace
String lineOfText = scanner.nextLine().trim();
Comments should ideally preceed the line, as it is easier to read and format, and more obvious that it is a comment. Also remove the redundant lineofText.trim(); later in the code.
Further, remember to close all Scanner instances when finished (so here one for each line, and one for the file).
The next problem is that in the inner loop, where you construct your ElectricTool instances, you are calling methods on scanner, rather than scanner2 (rename this to something more semantic, eg itemScanner):
Scanner itemScanner = new Scanner(lineOfText);
itemScanner.useDelimiter(",");
boolean mRechargeable = itemScanner.nextBoolean();
String mPower = itemScanner.next();
String mToolName = itemScanner.next();
String mItemCode = itemScanner.next();
int mTimesBorrowed = itemScanner.nextInt();
boolean mOnLoan = itemScanner.nextBoolean();
int mCost = itemScanner.nextInt();
int mWeight = itemScanner.nextInt();

Sharepoint 2010 How to use "File Size" column value in a formula?

I am trying to use "File Size" (aka "FileSizeDisplay") in a Calculated column formula.
"File Size" is an existing column (default SP not custom).
But is not available in the "Insert Column" list of any library.
And SP displays an error message that states it does not exist if it is added to a formula manually as either [File Size] or [FileSizeDisplay].
All I want to do is inform a user that an image is too big. Not trying to prohibit file size upload or anything technical like that. Just want a Calculated column to display a message.
If the column value was available the following would work:
=IF([File Size]>50000,"Image is too big","Image is sized correctly")
or
=IF([FileSizeDisplay]>50000,"Image is too big","Image is sized correctly")
Any one know why this column is not available?
Cheers
You'll want to get the file size first: get file size then you can display of message in a pop up or how ever you'd like
using System;
using System.IO;
class Program
{
static void Main()
{
// The name of the file
const string fileName = "test.txt";
// Create new FileInfo object and get the Length.
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
// Change something with the file. Just for demo.
File.AppendAllText(fileName, " More characters.");
// Create another FileInfo object and get the Length.
FileInfo f2 = new FileInfo(fileName);
long s2 = f2.Length;
// Print out the length of the file before and after.
Console.WriteLine("Before and after: " + s1.ToString() +
" " + s2.ToString());
// Get the difference between the two sizes.
long change = s2 - s1;
Console.WriteLine("Size increase: " + change.ToString());
}
}

How to check a proper file in android phone's memory?

I need a method that downloads a picture and save it in SD card for later use. I got it finally, i just need an operation that checks if the file in already exists or not.
If not, the app will download it. If it is exitsts, my image view will use it.
So my question is just simple:
How to check a file in SD?
If i got this place for example:
String imageInSD = "/sdcard/1.png";
You can use the following code
String sdcardState = android.os.Environment.getExternalStorageState();
String fileName = "yourfilename" + ".png";
if (sdcardState.contentEquals(android.os.Environment.MEDIA_MOUNTED))
{
String destPath = android.os.Environment.getExternalStorageDirectory().toString()+ File.separator +fileName;
File output =new File(destPath);
if(output.exists())
\\it exists-use Imageview
else
\\Download the file accordingly
}
else
\\SDCARD not mounted

The process cannot access the file 'd:\1.doc' because it is being used by another process

my code :
object c = "d:\\1.doc";
if(File.Exists(c.ToString()))
{
File.Delete(c.ToString());
}
error :
The process cannot access the file 'd:\1.doc' because it is being used
by another process.
How close ? with code
first of all use string instead of object, so:
string c = "d:\\1.doc";
now as the message indicated the file being used by another process. either by windows process, or you are opening the file stream and forget to close it. check in your code where you are interacting with the file.
Edit: Since you are using Microsoft.Office.Interop.Word make sure you close the file(s) open first like:
Word.ApplicationClass word = new Word.ApplicationClass();
//after using it:
if (word.Documents.Count > 0)
{
word.Documents.Close(...);
}
((Word._Application)word.Application).Quit(..);
word.Quit(..);
I had the same type of issue when I wanted to Delete File after Open/Read it using Microsoft.Office.Interop.Word and I needed to close my document and the application like that :
private void parseFile(string filePath)
{
// Open a doc file.
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document document = application.Documents.Open(filePath);
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
Console.WriteLine("Word {0} = {1}", i, text);
}
// Close document correctly
((_Document)document).Close();
((_Application)application).Quit();
}
You have that file actively open in this or another program, and Windows prevents you from deleting it in that case.
Check if the file still running (opened) by another application
1- Microsoft Word
2- WordPad

Resources