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

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

Related

FolderBrowserDialog last Folder Name

I'm new to C++/CLI and have a Question about the FolderBrowserDialog function.
Using ->SelectedPath gives me "C:\Folder\Subfolder\Selected Folder"
How can I save JUST "Selected Folder" to a string?
FolderBrowserDialog^ DestinationFolderDialog;
DestinationFolderDialog = gcnew System::Windows::Forms::FolderBrowserDialog;
System::Windows::Forms::DialogResult result = DestinationFolderDialog->ShowDialog();
if (result == System::Windows::Forms::DialogResult::OK)
{
String^ path = DestinationFolderDialog->SelectedPath;
SetDestinationPath(path);
lblDestinationPath->Text = path;
}
The way I set my Destination Path
And now I want to work with it
String^ pathSource = GetSourcePath();
String^ pathDest = GetDestinationPath();
Im trying to generate Symlinks.
So im Selecting "Y:\Movies\Movie_a" as Source
And im Selecting "X:\" as Destination for my Symlink Folder
To Create it I need to add "Movie_a" to "X:\"
Can someone help me?
If what you want is to extract the last dir name from C:\Folder\Subfolder\Selected Folder then you can:
use Path.GetFileName method to acquire the last part from the path
call String.Split with the Path.PathSeparator and take the last array element
Updated in respect to #LucasTrzesniewski comment

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

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();

Image saving and retrieving from database

I have to take an image from my system and save it in the form of bytes to a folder in the server.Than i have to give the path of the .txt file i.e the converted image file to the database by creating a table in it.Finally i want to retrieve it from the database.It should be a windows application.Is this possible?
Yes it is possible...
You are just storing the path of the image file that you created.
The path is just going to be a simple string.
While retrieving, you need to take the path from the database and set it as the image source path to the ImageBox in the windows application.
Example:
for selecting the image file.
string DestinationPath = "D:\\test.jpg";
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
byte[] bt = File.ReadAllBytes(ofd.FileName);
File.WriteAllBytes(DestinationPath, bt);
}
//Store DestinationPath into the database.
for retrieving and displaying in a PictureBox
string pathFromDatabase = "D:\\test.jpg"; //Retrieve from database
pboxDisplay.Image = Image.FromFile(pathFromDatabase); //Assuming pboxDisplay as the PictureBox control
hope it helps...
try this
from data base
byte bt = File.ReadAllBytes("C:\\test.jpg");
File.WriteAllBytes("C:\\test1.jpg",bt)
" bt " you can upload this byte to Database while retrieving bytes from data base use File.WriteAllbytes ...

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

How to work around the [1] IE bug while saving an excel file from a Web server?

I've noticed that Internet Explorer adds a number in square brackets to files downloaded from the internet (usually [1]). This creates a big problem with downloading Excel spreadsheets as square brackets are not a valid filename character inside Excel worksheet name. That problem is IE specific, others browsers are keeping same file name.
So, if you have a pivot table auto-refreshed on file opening for example, you'll get an error message saying the name "file[1].yourPivotTableName" is not valid.
Is there any solution to that problem ?
EDIT : It seems that whatever the filename suggested by HTTP directives, IE adds [1] in all cases, which cause the problem ! (So, answers about filenames aren't helpful in that case)
EDIT : I've tried some VBA code to save file under another name when it'll open. However, it doesn't work (same error message than before). Do you think there's a way to fix that with VBA ?
I've got it working using VBA provided by this cool guy (think of him fondly).
It renames the file and then reattaches the pivots.
http://php.kennedydatasolutions.com/blog/2008/02/05/internet-explorer-breaks-excel-pivot-tables/
I think that this happens when you open the spreadsheet in IE and IE saves it to a temporary file. And I think it only happens when the spreadsheet's filename has more than one dot in it. Try it with a simple "sample.xls".
Another workaround is to tell users to save the file to the desktop and then open it.
It's a built-in feature in Internet Explorer.
Stop using "Open", start using "Save" in the file-download window, otherwise IE will append "[1]" to filename of the file that it places in some temporary folder.
You could build some .NET application using System.IO.FileSystemWatcher that catches the event of the creation of the downloaded file or something and renames the file.
I have solved this issue by using method where we pass 3 parameters: Filename, file extension(without the .dot) and the HTTP request); then doing the UTF-8 encoding of the filename and extension.
Sample Code:
public static String encoding(String fileName, String extension, HttpServletRequest request)
{
String user = request.getHeader( "user-agent" );
boolean isInternetExplorer = ( user.indexOf( "MSIE" ) > -1 );
String var = "";
try
{
fileName = URLEncoder.encode( fileName, "UTF-8" );
fileName = fileName.trim().replaceAll( "\\+", " " );
extension = URLEncoder.encode( extension, "UTF-8" );
extension = extension.trim().replaceAll( "\\+", " " );
if ( isInternetExplorer )
{
disposition = "attachment; filename=\"" + fileName+"."+extension+"\"";
}
else
{
var = "attachment; filename*=UTF-8''" + fileName+"."+extension;
}
}
catch ( UnsupportedEncodingException ence )
{
var = "attachment; filename=\"" + fileName+"."+extension;
ence.printStackTrace();
}
return var;
}
This worked just fine in my case.
Hope it will help you all.
Actually, the correct .NET-code is as following:
Response.AppendHeader("content-disposition", "attachment;filename=file.xls");
Response.ContentType = "application/vnd.ms-excel";
Note: AppendHeader, not AddHeader, which I think only works in debug web-server and IIS7.
The following has worked for me:
private string EncodeFileName(string fileName)
{
fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", " ");
if (HttpContext.Current.Request.UserAgent.ToLower().Contains("msie"))
{
var res = new StringBuilder();
var chArr = fileName.ToCharArray();
for (var j = 0; j < chArr.Length; j++)
{
if (chArr[j] == '.' && j != fileName.LastIndexOf("."))
res.Append("%2E");
else
res.Append(chArr[j]);
}
fileName = res.ToString();
}
return "\"" + fileName + "\"";
}
You could just make sure that in the options box for the pivot the auto refresh is switched off. Now even when opened from the server the pivot will work perfectly
I have encountered the same problem and came up with (imo) a better solution that does not need any VBA.
If you set "Content-Disposition" header to "attachment; filename=<...>" instead of "inline; filename=<...>" the normal browsers will open dialog that will allow to save or open a file with a filename defined in a header, but Internet Explorer will behave in kind of weird way. It will open file download dialog and if you press Save it will suggest a filename that is defined in the header, but if you press Open it will save file to a temporary folder and open it with a name that is the same as your URN (without 'namespace'), e.g. if your URI is http://server/folder/file.html, so IE will save your file as file.html (no brackets, woo hoo!). This leads us to a solution:
Write a script that handles request from http://server/folder/* and when you need to serve an XLS file just redirect to that script (use your filename instead of asterisk) with Content-Disposition set to inline.
Put these four lines in your code:
response.reset();
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate,post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
Hope this helps.
In .NET I have found from experience only this seems to work for me:
Response.AddHeader("Content-Disposition", "attachment; filename=excel.xls");
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.ContentType = "application/vnd.ms-excel";
The duplication smells, but so far I have never got to the bottom of it (maybe Sebs post explains this). Also the "content-Disposition" value appears very finicky use a : instead of a ; or ommit the space between it and 'filename' and it blows!
Also if you have compression enabled on IIS this may fix things for you:
Response.ClearHeaders()

Resources