I am trying to list all the PDF files from the external storage created by the app. How to list pdf files in the App after iterating through cursor?
private void getExternalPDFFiles() {
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
// every column, although that is huge waste, you probably need
// BaseColumns.DATA (the path) only.
String[] projection = null;
// exclude media files, they would be here also.
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE;
String[] selectionArgs = null; // there is no ? in selection so null here
String sortOrder = null; // unordered
// Cursor allNonMediaFiles = cr.query(uri, projection, selection, selectionArgs, sortOrder);
// only pdf
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String[] selectionArgsPdf = new String[]{mimeType};
Cursor cursor = cr.query(uri, projection, selectionMimeType, selectionArgsPdf, sortOrder);
assert cursor != null;
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//your code to implement
Log.d("TAG", cursor.getColumnNames().toString());
cursor.moveToNext();
}
}
Log.d("TAG", cursor.getCount() + "");
Log.d("TAG", cursor.getColumnCount() + "");
cursor.close();
}
Get all file list with Uri and FileName in Android-10 and above:
class FileModel {
String displayName;
Uri fileUri;
FileModel(String displayName, Uri fileUri) {
this.displayName = displayName;
this.fileUri = fileUri;
}
}
...
private ArrayList<FileModel> getExternalPDFFileList() {
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE;
String[] selectionArgs = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String[] selectionArgsPdf = new String[]{mimeType};
Cursor cursor = cr.query(uri, projection, selectionMimeType, selectionArgsPdf, null);
assert cursor != null;
ArrayList<FileModel> uriList = new ArrayList<>();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int columnIndex = cursor.getColumnIndex(projection[0]);
long fileId = cursor.getLong(columnIndex);
Uri fileUri = Uri.parse(uri.toString() + "/" + fileId);
String displayName = cursor.getString(cursor.getColumnIndex(projection[1]));
uriList.add(new FileModel(displayName, fileUri));
}
cursor.close();
return uriList;
}
i want to upload files to ftp but i get an error
The given path's format is not supported.
i have mention my code below kindly help me.
the path giving error , what should i need to keep path like ?
the following is my path
this.path = #"ftp://ip address/Requests/";
public bool UploadDocsToFTP(string SourceFilePath, string FileName)
{
string ServerUri = "";
string FTPUserName = "";
string FTPPassword = "";
string ftpURI = "";
try
{
try
{
ServerUri = ConfigurationManager.AppSettings["LinuxFileServerUri"];
FTPUserName = ConfigurationManager.AppSettings["LinuxFtpUserName"];
FTPPassword = ConfigurationManager.AppSettings["LinuxFtpPassword"];
string[] splitfilename = SourceFilePath.Split('\\');
//String businesRegId = splitfilename[2];
//String userRegId = splitfilename[3];
//String folderType = splitfilename[3];
//ftpURI = "ftp://" + ServerUri + "//" + businesRegId + "//" + userRegId;
//if (!string.IsNullOrEmpty(folderType))
// ftpURI += "//" + folderType;
//ServerUri = "ftp://" + ServerUri + "//" + businesRegId + "//" + userRegId + "//";
//if (!string.IsNullOrEmpty(folderType))
// ServerUri += folderType + "//";
// SetMethodRequiresCWD();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ip address/Requests" + FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
FileStream fs = File.OpenRead(SourceFilePath + FileName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (WebException e)
{
String status = ((FtpWebResponse)e.Response).StatusDescription;
if (UploadDocsToFTP_DirNotExists(SourceFilePath, FileName))
{
return true;
}
return false;
}
}
catch (Exception ex)
{
ex.ToString();
return false;
}
return true;
}
A URL (which is what your path is) cannot contain spaces or other certain characters, so you have to encode it.
You can use System.Net.WebUtility for this.
// instead of this:
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ip address/Requests" + FileName);
// do this:
string path = System.Net.WebUtility.UrlEncode("ftp://ip address/Requests" + FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
Can anyone help me how to encrypt a file using a existing encryption script batch file in c# using ProcessStartInfo class?
I am new to the Encryption of a file. I am passing a parameter path, path of text file that I need to encrypt.
This is path of my encryption script batch file
D:\CBMS-Keenan\core\Transmittals\Scripts\123gpg.bat|gpg||false
This is my existing code
public string PerformAction(string path)// Path input file name path(.txt)
{
//TransmittalBatch batch = new TransmittalBatch();
string _transmitfile=string.Empty;
string text1 = "";
string batchfilename=Path.GetFileName(path);
string renamedfile = "";
if((this._filename!=null)&& (this._filename.Length > 0))
{
renamedfile = this._filename;
}
else
{
if(this._replacesuffix)
{
renamedfile = batchfilename.Remove(batchfilename.LastIndexOf("."));
}
else
{
renamedfile = batchfilename;
}
if((this._suffix!=null)&&(this._suffix.Length>0))
{
renamedfile = renamedfile + "." + this._suffix.Replace(".", "");
}
}
if ((batchfilename != null) && (batchfilename.Length > 0))
{
ProcessStartInfo _info = new ProcessStartInfo(this._scriptfile, "\"" + batchfilename + "\"\"" + renamedfile + "\"");//this._scriptfile is encryprtion batch file //batchfilename is input batch file which we got from the path//renamed file is the filerenamed after the encryption
_info.CreateNoWindow = true;
_info.RedirectStandardOutput = true;
_info.RedirectStandardInput = true;
_info.RedirectStandardError = true;
_info.UseShellExecute = false;
Process _process = Process.Start(_info);
StreamReader _streamreader1 = _process.StandardOutput;
StreamReader _streamreader2 = _process.StandardError;
_process.WaitForExit(300000);
if(_process.HasExited)
{
text1 = _streamreader1.ReadToEnd();
text1 = text1 + "Errors:\r\n";
text1 = text1 + _streamreader2.ReadToEnd();
}
//batch.RuleActionResults["LatestWorkingFilename"] = text3;
_process.StandardInput.WriteLine(text1);
_transmitfile = renamedfile;
}
else
{
text1 = "No files to encrypt!";
}
//batch.RuleActionResults["Encryption Results"] = text1;
string _ecnryptedfile = text1;
//Console.WriteLine("Encrypted result:" + _ecnryptedfile);
return _transmitfile;
//return batch.RuleActionResults["EncryptionResults"].ToString();
}
I am developing silverlight web part by using the client object model. I am getting the bitmap image from sharepoint server. Now I want to save this bitmap image in isolated storage. So I am using following code
WriteableBitmap wb = new WriteableBitmap(attachments);
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("abcd1.jpg", FileMode.Create, isoFile))
{
using (StreamWriter sw = new StreamWriter(isoStream))
{
sw.Write(wb.ToByteArray());
}
}
}
Now I am seeing the saved image at location C:\Users\Rent2\AppData\LocalLow\Microsoft\Silverlight\is\vzvpufsm.s4i\m0laonzr.til\1\s\nkhajster01es5wdoyfxd0n5rd2dls3ovyu4wcdig04zjx44hyaaafea\f
When I click on it, it gives me message as "Invalid Image". Can you please tell me how should i write code so that I can see the actual image after saving it in isolated storage ?
private void zipFile()
{
context = Microsoft.SharePoint.Client.ClientContext.Current;
Microsoft.SharePoint.Client.File.OpenBinaryDirect(
context,
#"/TemplateInvoice/" + App.templateFileName + ".xlsx", successFile, FailFile);
}
private void successFile(object sender, OpenBinarySucceededEventArgs args)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Obtain the isolated storage for an application.
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
Stream strm = args.Stream;
using (var isoStream = store.OpenFile(App.templateFileName + ".zip", FileMode.OpenOrCreate))
{
// Read the resource file into a byte array.
bytes = new byte[strm.Length];
int numBytesToRead = (int)strm.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = strm.Read(bytes, numBytesRead, numBytesToRead);
// The end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
// Write the byte array to the IsolatedStorageFileStream.
isoStream.Write(bytes, 0, numBytesToRead);
//isoStream.Dispose();
}
strm.Close();
string path = App.templateFileName + ".zip";
ZipHelp.UnZip(path, System.IO.Path.GetDirectoryName(path), 4096);
replaceFileContent();
string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(path);
string fileName = ZipHelp.Zip(rootDirectory.Replace(".zip", ""), invoice);
//string filename = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "Invoice1.xlsx";
// Read the resource file into a byte array.
using (var stream = store.OpenFile(fileName, FileMode.Open))
{
bytes = new byte[stream.Length];
int numBytesToRead = (int)stream.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = stream.Read(bytes, numBytesRead, numBytesToRead);
// The end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
InvoiceTemplete invoiceTemplate = new InvoiceTemplete(fileName, bytes, SetMessage);
invoiceTemplate.AddDocument(invoiceTemplate);
}
}
//mark rows as billed
foreach (var item in PrivatePayList)
{
MedwaiverViewModel MedwaiverViewModelObj = new MedwaiverViewModel();
MedwaiverViewModelObj.ChangeBillingStatus(item.ListItemId, "Billed");
if (MedwaiverTimeLogList != null)
{
MedwaiverTimeLogList.Remove(item);
}
if (ClientSpecificTimeLogList != null)
{
ClientSpecificTimeLogList.Remove(item);
}
if (rangeBoundTimeLogListForDate != null)
{
rangeBoundTimeLogListForDate.Remove(item);
}
if (vRangeBoundTimeLogListForDateAndClient != null)
{
vRangeBoundTimeLogListForDateAndClient.Remove(item);
}
}
}
catch (IsolatedStorageException isx)
{
MessageBox.Show(isx.Message);
}
});
}
private void FailFile(object sender, OpenBinaryFailedEventArgs e)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Fail");
});
}
//The following class zip and unzip the file
class ZipHelp
{
static List<string> folderPathList = new List<string>();
public static string Zip(string rootDirectory, string fileName)
{
byte[] buffer;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream zipFileStream = store.CreateFile(fileName + ".xlsx");
ZipOutputStream zipOutStream = new ZipOutputStream(zipFileStream);
zipOutStream.UseZip64 = UseZip64.Off;
//zipOutStream.CanPatchEntries
foreach (var item in folderPathList)
{
string entryName = "";
buffer = new byte[4096];
if (item.Substring(0,1) == #"/")
{
//removes leading /
entryName = item.Substring(1);
}
else
{
entryName = item;
}
ZipEntry entry = new ZipEntry(entryName);
//entry.CompressionMethod = CompressionMethod.Deflated;
//entry.
entry.IsZip64Forced();
//entry.IsDirectory
zipOutStream.PutNextEntry(entry);
using (IsolatedStorageFileStream stream = store.OpenFile(rootDirectory + #"\" + item, FileMode.Open))
{
int size;
do
{
size = stream.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
stream.Close();
}
}
zipOutStream.Close();
zipFileStream.Close();
}
return fileName + ".xlsx";
//string[] directories = GetLocationTypes();
//zip();
//string[] filenames = Directory.GetFiles(directories);
//using (var store = IsolatedStorageFile.GetUserStoreForApplication())
//{
// using (var isoStream = store.OpenFile("#" + rootDirectory, FileMode.OpenOrCreate))
// {
// //foreach(string dir in
// }
//}
}
private static string[] GetLocationTypes()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
return store.GetDirectoryNames();
}
}
/// <summary>
/// UnZip a file
/// </summary>
/// <param name="SrcFile">source file path</param>
/// <param name="DstFile">unzipped file path</param>
/// <param name="BufferSize">buffer to use</param>
public static void UnZip(string SrcFile, string DstFile, int BufferSize)
{
folderPathList.Clear();
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
FileStream fileStreamIn = store.OpenFile(SrcFile, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(SrcFile);
rootDirectory = rootDirectory.Replace(".zip", "");
store.CreateDirectory(rootDirectory);
while (true)
{
ZipEntry entry = zipInStream.GetNextEntry();
if (entry == null)
break;
if (entry.Name.Contains("/"))
{
string[] folders = entry.Name.Split('/');
string lastElement = folders[folders.Length - 1];
var folderList = new List<string>(folders);
folderList.RemoveAt(folders.Length - 1);
folders = folderList.ToArray();
string folderPath = "";
foreach (string str in folders)
{
folderPath = folderPath + "/" + str;
if (!store.DirectoryExists(rootDirectory + "/" + folderPath))
{
store.CreateDirectory(rootDirectory + "/" + folderPath);
}
}
folderPath = folderPath + "/" + lastElement;
writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, folderPath);
}
else
{
writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, entry.Name);
}
}
zipInStream.Close();
fileStreamIn.Close();
}
private static void writeToFile(int BufferSize, FileStream fileStreamIn, ZipInputStream zipInStream, string rootDirectory, string folderPath)
{
IsolatedStorageFile store1 = IsolatedStorageFile.GetUserStoreForApplication();
FileStream fileStreamOut = store1.OpenFile(rootDirectory + "/" + folderPath, FileMode.Create, FileAccess.Write);
folderPathList.Add(folderPath);
int size;
byte[] buffer = new byte[BufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Close();
}
}
I can think of two viable options here.
In your code above, save off the Pixels array of the WriteableBitmap. Then to restore it, you would create a WriteableBitmap of the appropriate size and the set the Pixels array to the stored data.
-or-
Use a HttpWebRequest or WebClient request to get the raw image stream and save that to IsolatedStorage.
There are pros and cons to each of these, in the first case the data is uncompressed and will take up more space in isolated storage and you would not be able to open the image from disk outside of Silverlight, similar to the issue you had above. For the second option you can run into cross domain issues if the images are on a different server than your Silverlight XAP file and it's also a bit more complex to implement.
The basic problem is that you're storing the decoded RGBA pixels array as a JPEG file - but they're not the same. Your code is basically correct: you just can't use this method to store it as a JPEG file. But if you happen to know that the image is, say, 800x600, you could create an 800x600 WriteableBitmap, and then set the Pixels property to the retrieved stream's byte array. Or if you don't know the dimensions when you're retrieving it, you could store the dimensions as the first two integers in the stream (before you write the pixels to the stream), and read out the dimensions when you're reading the file. You'd effectively be creating your own very simplistic .bmp format.
I want to store image into my datatable and while adding colum I want to set its default value, sending you code doing with checkboxes..
public void addCheckBoxesRuntime(){
for (int i = 0; i < InformationOne.Length; i++)
{
dt = new DataColumn(InformationOne[i][1] + " (" + InformationOne[i][0] + " )");
dt.DataType = typeof(Boolean);
viewDataTable.Columns.Add(dt);
dt.DefaultValue = false;
}
}
Make a DataColumn with type string and then store the string binary of the image into the field. Alternatively, use the binary itself with a byte[].
Should work 100%.
Something along the lines of this:
public string ImageConversion(System.Drawing.Image image)
{
if (image == null)
return string.Empty;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);
string value = string.Empty;
for (int intCnt = 0; intCnt <= memoryStream.ToArray.Length - 1; intCnt++)
{
value = value + memoryStream.ToArray(intCnt) + ",";
}
return value;
}
}